import Mathlib.Computability.Partrec import Mathlib.Computability.PostTuringMachine import Mathlib.Computability.Primrec import Mathlib.Computability.TMToPartrec import Mathlib.Data.Fintype.EquivFin import Mathlib.Data.Fintype.Option import Mathlib.Data.Fintype.Prod import Mathlib.Data.List.FinRange import Std set_option maxErrors 1000 set_option backward.isDefEq.respectTransparency.types false set_option maxHeartbeats 250000 set_option linter.unusedSimpArgs false private theorem p455MapFinRange (n : ℕ) : (List.finRange n).map Fin.val = List.range n := by apply List.ext_getElem <;> simp /- Begin Problem455MachineLocal (from finite-semigroup-identity-bases). -/ section namespace P455MachineLocal inductive Direction | left | stay | right deriving DecidableEq structure Ins (A Q : Type) where state : Q symbol : A dir : Direction deriving DecidableEq structure Cell (A Q : Type) where sym : A head : Option Q deriving DecidableEq def action (d : Q→A→Ins A Q) (c : Cell A Q) := c.head.map fun q=>d q c.sym def sends (i : Ins A Q) (toward : Direction) : Option Q := if i.dir=toward then some i.state else none def 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 none else some ⟨a.symbol,sends a .stay⟩ | _,_,_ => none def 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_instance def dest (dir : Direction) (p : Nat) : Nat := match dir with | .left => p-1 | .stay => p | .right => p+1 def writeAt (tape : Nat→A) (p : Nat) (a : A) (x : Nat) := if x=p then a else tape x private 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 := by by_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 := by by_cases e : x=0 · subst x; simp [leftOf] · have eq : (x-1=p) ↔ x=p+1 := by omega simp [leftOf,e,center_action,eq] private theorem right_action (d : Q→A→Ins A Q) (tape : Nat→A) (p w : Nat) (hp : p simp [leftOf,e] private theorem right_boundary (row : Nat→α) (w x : Nat) : (rightOf row w x).isNone=true ↔ x+1=w := by by_cases e : x+1=w <;> simp [rightOf,e] /-- When an entire bounded row has one head, the local rule at that head is 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 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 have pos : p≠0 := by simpa [exits,dir] using safe simp [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 omega simp 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 P455MachineLocal end /- Begin Problem455Quotient (from finite-semigroup-identity-bases). -/ section namespace P455Quotient abbrev 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 c namespace Walk theorem trans {s : α → α → Prop} (h : Walk s x y) (k : Walk s y z) : Walk s x z := by induction k with | refl => exact h | snoc _ step ih => exact .snoc ih step theorem symm {s : α → α → Prop} (rev : ∀ {x y}, s x y → s y x) (h : Walk s x y) : Walk s y x := by induction h with | refl => exact .refl _ | snoc _ step ih => exact (Walk.snoc (.refl _) (rev step)).trans ih theorem 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 := by induction h with | refl => exact px | snoc _ move ih => exact step move ih end Walk section variable {α : Type} [DecidableEq α] local notation "W" => Word α def Cap (r : Nat) (u : W) : Prop := ∀ a : α, u.count a ≤ r structure Rules (α : Type) [DecidableEq α] where r : Nat step : Word α → Word α → Prop reverse : ∀ {u v}, step u v → step v u counts : ∀ {u v}, step u v → ∀ a, u.count a = v.count a extend : ∀ {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 v def Factor (u v : W) := ∃ l t : Word α, v = l ++ u ++ t def Good (T u : W) := ∃ v, Variant R T v ∧ Factor u v theorem count_walk {u v : W} (h : Walk R.step u v) (a : α) : u.count a = v.count a := by induction 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) := by induction h with | refl => exact .refl _ | snoc pre mv ih => apply Walk.snoc ih (R.extend mv l t ?_) intro a have eq := count_walk R pre a have bound := hc a simp only [List.count_append] at * omega theorem 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) := by suffices 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 variant have bound : Cap R.r ((left ++ l) ++ x ++ (t ++ right)) := by intro a have e := count_walk R reach a simp only [List.count_append] at * have := hc a omega have ext := contextual_walk R path (left ++ l) (t ++ right) bound simp 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 := by obtain ⟨_, reach, l, t, rfl⟩ := h intro a have e := count_walk R reach a have b := hc a simp only [List.count_append] at e omega theorem factor_good {T u v : W} (g : Good R T v) (f : Factor u v) : Good R T u := by obtain ⟨w, path, l, t, hw⟩ := g obtain ⟨l', t', hv⟩ := f exact ⟨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) | _, _ => none def Live (T : W) : Raw α → Prop | none => False | some u => Good R T u def 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 v theorem rel_refl (T : W) (x : Raw α) : Rel R T x x := by by_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 := by rintro (⟨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 := by rintro (⟨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 e exact Or.inr ⟨u,w,rfl,rfl,gu,gw,h.trans h'⟩ def setoid (T : W) : Setoid (Raw α) where r := Rel R T iseqv := ⟨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) := by cases 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) := by rcases 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 t by_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) := by apply 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 [] w cases 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 e def cls (T : W) (x : Raw α) : Q R T := Quotient.mk _ x set_option backward.isDefEq.respectTransparency false in def 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 none def 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) := by induction 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 in theorem 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 := by refine 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 a change cls R T (mulRaw (some []) a) = cls R T a ∧ cls R T (mulRaw a (some [])) = cls R T a cases a <;> simp only [mulRaw, List.nil_append, List.append_nil, and_self] set_option backward.isDefEq.respectTransparency false in theorem 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 := by induction 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 := by constructor · intro h by_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 eq have e : Rel R T (some u) none := Quotient.exact eq rcases e with ⟨bad,_⟩ | ⟨_,_,_,e,_,_,_⟩ · exact bad good · contradiction theorem 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 := by constructor · intro e have h : Rel R T (some u) (some v) := Quotient.exact e rcases h with ⟨bad,_⟩ | ⟨_,_,ea,eb,_,gv,path⟩ · exact (bad g).elim · cases ea cases eb exact ⟨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 = [] := by constructor · intro eq have path := ((same_nonzero_class R (good_empty R T)).mp eq.symm).2 exact (List.Perm.nil_eq (List.perm_iff_count.mpr (count_walk R path))).symm · rintro rfl; rfl theorem nonzero_representative {T : W} (q : Q R T) (nz : q ≠ zero R T) : ∃ u, Good R T u ∧ ofWord R T u = q := by induction 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) := by induction v with | nil => rfl | cons x xs ih => rw [eval, ← reps x (by simp), ih (fun y hy => reps y (by simp [hy]))] rfl theorem 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 := by rw [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 := by induction 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 hx rcases 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 move still 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 := by obtain ⟨z,l,t,path,eq⟩ := (arbitrary_representatives R hc a v h reps).mp nz exact ⟨z,l,t,path,eq,path.transport initial one⟩ end end P455Quotient end /- Begin Problem455Slots (from finite-semigroup-identity-bases). -/ section namespace Problem455.Slots abbrev Word := List Nat abbrev Event := Nat × Nat def advance (n : Nat → Nat) (w : Word) : Nat → Nat := fun a => n a + w.count a def stamp (n : Nat → Nat) : Word → List Event | [] => [] | a :: w => (a, n a) :: stamp (advance n [a]) w def events (w : Word) := stamp (fun _ => 0) w theorem advance_append (n : Nat → Nat) (u v : Word) : advance (advance n u) v = advance n (u ++ v) := by funext a simp [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 := by induction 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] rfl theorem 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)) := by induction u generalizing n with | nil => rfl | cons a u ih => obtain ⟨fresh, rest⟩ := List.nodup_cons.mp nd simp only [stamp, List.map_cons] rw [hm a (by simp), ih _ rest] intro b hb have 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) where pre : Word p : Word q : Word post : Word dp : p.Nodup dq : q.Nodup disjoint : ∀ a ∈ p, a ∉ q indexP : ∀ a ∈ p, pre.count a = m indexQ : ∀ a ∈ q, pre.count a = m def 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)) := by let n := fun a => s.pre.count a have 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.indexP have hq : stamp n s.q = tagged m s.q := stamp_at _ _ _ s.dq s.indexQ have hp' : stamp (advance n s.q) s.p = tagged m s.p := by apply stamp_at _ _ _ s.dp intro a ha simp [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 := by apply stamp_at _ _ _ s.dq intro a ha have fresh : a ∉ s.p := fun hp => s.disjoint a hp ha simp [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 := by funext a simp [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 = [] := by apply List.filter_eq_nil_iff.mpr simpa using h theorem 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))) := by rcases 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 _ _ _ _ nc theorem 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)) := by obtain ⟨lo, hi, h, h'⟩ := move_events s rw [h, h'] apply selected_swap simpa [tagged] using nc /- Observable order measured directly by the sublist relation on the word of 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 := by constructor · intro h exact h.trans (List.filter_sublist ..) · intro h have hf := h.filter (fun x => decide (x ∈ t)) have self : t.filter (fun x => decide (x ∈ t)) = t := by apply List.filter_eq_self.mpr simp rwa [self] at hf theorem 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 := by unfold sees rw [← 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 := by apply sees_invariant left exact fun a _ he => hm (a,m) he rfl /- An occupant can have mutable occurrence index. Only the two specified owner endpoints must be immutable. This covers unit-erasing as well as multiletter 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)] := by apply sees_invariant by_cases h : e.1 ∈ s.p · right intro a ha have diff : (a,m) ≠ e := by intro eq have : a = e.1 := congrArg Prod.fst eq exact s.disjoint e.1 h (this ▸ ha) simp [diff, Ne.symm hi, Ne.symm hj] · left intro a ha have diff : (a,m) ≠ e := by intro eq have : a = e.1 := congrArg Prod.fst eq exact 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 = 11 def 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 := by have h1 : i ≠ 14+k := by unfold slotStart at hi; omega have h2 : i+1 ≠ 14+k := by unfold slotStart at hi; omega exact 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 bit theorem tag_length (a b : Nat) (tag : List Bool) : (tag.flatMap (pair a b)).length = 2 * tag.length := by induction tag with | nil => rfl | cons bit t ih => cases bit <;> simp [pair, ih] <;> omega theorem profile_prefix_length (a b : Nat) (tag : List Bool) : (profilePrefix a b tag).length = 2 * (14+tag.length) := by unfold profilePrefix simp only [List.length_append, tag_length] change 6 + 20 + (2*tag.length) + 2 = _ omega theorem length_select_pair (a b : Nat) (hab : a ≠ b) (w : Word) : (select [a,b] w).length = w.count a + w.count b := by induction w with | nil => rfl | cons c w ih => unfold select at * simp at ih by_cases hca : c = a · subst c simp [List.count_cons, hab, Ne.symm hab, ih]; omega · by_cases hcb : c = b · subst c simp [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] := by induction w with | nil => simp at ha | cons c w ih => obtain ⟨hc,ht⟩ := List.nodup_cons.mp hd by_cases hca : c = a · subst c have hnil : select [a,b] w = [] := by apply select_nil intro x hx simp 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 ha have 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 := by unfold select apply List.filter_congr intro 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)) := by rintro ⟨old,h⟩ have eqPre : lo = fixed := by have ht := congrArg (List.take lo.length) h simpa [len] using ht subst fixed have he := List.append_cancel_left h have eqHi : hi = tail := by have hd := congrArg (List.drop 2) he cases bit <;> cases old <;> simpa [pair] using hd exact ⟨!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 := by let keep := [a,b] by_cases hp : ∀ x ∈ s.p, x ∉ keep · intro e unfold typed at * rw [← protected_projection s [a,b] (.inl hp)]; exact e by_cases hq : ∀ x ∈ s.q, x ∉ keep · intro e unfold typed at * rw [← protected_projection s [a,b] (.inr hq)]; exact e have shape : (a ∈ s.p ∧ b ∈ s.q) ∨ (b ∈ s.p ∧ a ∈ s.q) := by by_cases hap : a ∈ s.p · left refine ⟨hap,?_⟩ apply Classical.byContradiction intro hbn apply hq intro x hx simp 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 := by apply Classical.byContradiction intro hbn apply hp intro x hx simp only [keep, List.mem_cons, List.not_mem_nil, or_false, not_or] exact ⟨fun eq => hap (eq ▸ hx), fun eq => hbn (eq ▸ hx)⟩ right refine ⟨hbp,?_⟩ apply Classical.byContradiction intro han apply hq intro x hx simp 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 := by rcases 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 := by rw [length_select_pair a b hab, ca, cb, hm, profile_prefix_length]; omega unfold typed before after profile simp 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 bit end Problem455.Slots end /- Begin Problem455Closure (from finite-semigroup-identity-bases). -/ section namespace P455Closure universe u variable {α : 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, and before 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) where pHead : α pTail : List α qInit : List α qLast : α tag : List Bool middle : List (List α × Bool) beforeMutable : List α beforeFinalP : List α beforeFinalQ : List α namespace Frame variable (f : Frame α) def p := f.pHead :: f.pTail def q := f.qInit ++ [f.qLast] def pair (b : Bool) := if b then f.q ++ f.p else f.p ++ f.q def early := f.p ++ f.p ++ f.q ++ f.p ++ f.q ++ f.q def 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 copies of each block exhaust its alphabet; all intervening fillers are inert for 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 := by cases b <;> simp [core, pair, List.count_append] <;> omega omit [DecidableEq α] in theorem core_starts (b : Bool) : ∃ tail, f.core b = f.pHead :: tail := by simp [core, early, p] omit [DecidableEq α] in theorem core_ends (b : Bool) : ∃ ini, f.core b = ini ++ [f.qLast] := by unfold core q rw [← List.append_assoc] exact ⟨_, rfl⟩ private theorem count_tag_pairs (tag : List Bool) (side : Bool) : (tag.flatMap phasePair).count side = tag.length := by induction 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 := by cases side <;> simp [fixedPhases,count_tag_pairs,phasePair,List.count_cons,Nat.add_comm, List.replicate_succ] <;> omega private 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 := by induction es with | nil => simp | cons hd es ih => obtain ⟨w,b⟩ := hd cases b <;> cases side <;> simp only [Bool.false_eq_true,if_false,if_true] at has <;> simp [List.count_cons] <;> omega private 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 := by have hcap := hc a have hpq : 1 ≤ f.p.count a ∨ 1 ≤ f.q.count a := ha.imp List.count_pos_iff.mpr List.count_pos_iff.mpr have h1 : 11 + f.tag.length ≤ f.mid.count a := by rcases hpq with hp | hq · have h := token_count_le f.p f.q a false (by simpa using hp) f.middle simpa [hmid,fixed_count,mid] using h · have h := token_count_le f.p f.q a true (by simpa using hq) f.middle simpa [hmid,fixed_count,mid] using h have h2 : 3 ≤ f.early.count a := by simp [early]; omega have h3 : 1 ≤ (f.pair bit).count a := by cases bit <;> simp [pair] <;> omega simp only [core,List.count_append] at hcap ⊢ omega /-- Every block label has zero-based occurrence index 14+k at the mutable pair. Counts are derived from the actual profile and the cap; neither an 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 := by exact 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 capped arrangement of the prescribed blocks, including arrangements with previously 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 := by have hc' : Cap r ([] ++ f.core false ++ []) := by intro z have hh := hc z have hd : (f.core bit).count z = (f.core false).count z := by cases bit with | false => rfl | true => exact f.count_core z true simp only [List.count_append,hd, List.count_nil] at * omega have idx := f.index_of_order hr hmid false [] [] hc' a ha have bound := hc' a have sup : 1 ≤ f.p.count a ∨ 1 ≤ f.q.count a := ha.imp List.count_pos_iff.mpr List.count_pos_iff.mpr simp only [List.nil_append,List.append_nil] at idx bound simp only [core,pair,Bool.false_eq_true,if_false,List.count_append] at idx bound ⊢ omega theorem 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 any moved 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 := by have hs := hf.2.2.2.2.2.2.2 a ha have hs' : (f.core bit).count a = r := by cases bit with | false => exact hs | true => exact (f.count_core a true).trans hs have hh := hc a simp only [List.count_append,hs'] at hh exact ⟨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 false def profileWord (x y : α) (tag : List Bool) (bit : Bool) : List α := (profileBits tag bit).map (fun b => if b then y else x) omit [DecidableEq α] in private 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) := by induction es with | nil => exact .slnil | cons e es ih => obtain ⟨w,b⟩ := e have one : [if b then y else x].Sublist (w ++ (if b then q else p)) := by apply List.sublist_append_of_sublist_right cases b <;> simp [hx,hy] exact one.append ih omit [DecidableEq α] in private 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) := by have px := List.singleton_sublist.mpr hx have qy := List.singleton_sublist.mpr hy have ea := ((((px.append px).append qy).append px).append qy).append qy have mi := middle_trace f.p f.q hx hy f.middle rw [order] at mi have swapped : ((phasePair bit).map (fun b => if b then y else x)).Sublist (f.pair bit) := by cases bit with | false => exact px.append qy | true => exact qy.append px have 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 whole omit [DecidableEq α] in private theorem pattern_length (x y : α) (tag : List Bool) (bit : Bool) : (profileWord x y tag bit).length = 2 * (16 + tag.length) := by have tl : (tag.flatMap phasePair).length = 2 * tag.length := by induction tag with | nil => rfl | cons b t ih => simp [phasePair,ih]; omega simp [profileWord,profileBits,fixedPhases,phasePair,List.replicate_succ,tl] omega private theorem select_length (x y : α) (w : List α) : (w.filter (fun a => decide (a = x ∨ a = y))).length ≤ w.count x + w.count y := by induction 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 ⊢ <;> omega theorem 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 := by have tr := f.profile_trace bit x y hx hy hf.2.2.1 have 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 := by apply List.filter_eq_self.mpr intro a ha obtain ⟨b,_,rfl⟩ := List.mem_map.mp ha cases b <;> simp [keep] have tt := tr'.filter keep rw [intact] at tt apply Eq.symm apply tt.eq_of_length_le have h := select_length x y (l ++ f.core bit ++ t) have h1 := hc x have h2 := hc y have hr := hf.1 change ((l ++ f.core bit ++ t).filter (fun a => decide (a = x ∨ a = y))).length ≤ _ rw [pattern_length] omega end Frame /-- A single literal permitted swap, with both words written in the same external 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 u variable {r : Nat} {Allowed : List Bool → Prop} {Mark : α → α → Prop} {u v : List α} namespace Move theorem count_eq (h : Move r Allowed Mark u v) (a : α) : u.count a = v.count a := by obtain ⟨f,b,l,t,_,hu,hv,_⟩ := h rw [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 := by obtain ⟨_,_,_,_,_,_,_,hc⟩ := h exact hc theorem cap_right (h : Move r Allowed Mark u v) : Cap r v := by intro a rw [← h.count_eq] exact h.cap_left a theorem symm (h : Move r Allowed Mark u v) : Move r Allowed Mark v u := by have hc := h.cap_right obtain ⟨f,b,l,t,hf,hu,hv,_⟩ := h exact ⟨f,!b,l,t,hf,hv,by simpa using hu,hc⟩ /-- Extending a factor-local move to any capped context uses the same literal 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) := by obtain ⟨f,b,i,j,hf,hu,hv,_⟩ := h refine ⟨f,b,l ++ i,j ++ t,hf,?_,?_,hc⟩ <;> simp [hu,hv,List.append_assoc] end Move omit [DecidableEq α] in /-- Two splittings of a word, when the prefix on the left avoids the displayed 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 := by induction 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).1 exact False.elim (ha (by simp [hx])) | cons y p => obtain ⟨hxy,hrest⟩ := List.cons.inj h obtain ⟨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 core whenever the left context avoids its first symbol and the right context 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 := by obtain ⟨s,hs⟩ := hfirst have h1 : l ++ (x ++ t) = i ++ a :: (s ++ j) := by simpa [hs,List.append_assoc] using h obtain ⟨d,hi,hxt⟩ := stripBefore h1 ha obtain ⟨k,hk⟩ := hlast have h2 : t.reverse ++ x.reverse = j.reverse ++ b :: (k.reverse ++ d.reverse) := by have h' : x ++ t = d ++ c ++ j := by simpa [hs,List.append_assoc] using hxt simpa [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 := by simpa [List.reverse_append] using congrArg List.reverse hj have hx : l ++ (x ++ t) = l ++ ((d ++ c ++ e.reverse) ++ t) := by simpa [hi,hj',List.append_assoc] using h exact ⟨d,e.reverse,hi,hj',List.append_cancel_right (List.append_cancel_left hx)⟩ /-- Restrict a witnessed global swap to a factor containing all copies of the boundary anchors. Saturation of the other moving labels is automatic 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 := by have hpl := cap f.pHead have hqt := cap f.qLast simp only [List.count_append,hp,hq] at hpl hqt have hpl' : l.count f.pHead = 0 := by omega have hqt' : t.count f.qLast = 0 := by omega obtain ⟨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 := by intro a have hh := cap a simp only [List.count_append] at hh omega refine ⟨d ++ f.core (!b) ++ e,⟨f,b,d,e,hf,hx,rfl,hxcap⟩,?_⟩ simp [hi,hj,List.append_assoc] end P455Closure end /- Begin Problem455Swap (from finite-semigroup-identity-bases). -/ section namespace Problem455Swap abbrev Word := List Nat def occ (a : Nat) : Word → Nat | [] => 0 | b :: w => (if a = b then 1 else 0) + occ a w def cap (r : Nat) (w : Word) : Prop := ∀ a, occ a w ≤ r def hit (x y : Nat) (left right : Option Nat) : Nat := if left = some x ∧ right = some y then 1 else 0 def bigram (x y : Nat) : Word → Nat | [] => 0 | a :: w => hit x y (some a) w.head? + bigram x y w def Link (r : Nat) (w : Word) (x y : Nat) : Prop := bigram x y w = r theorem occ_append (a : Nat) (u v : Word) : occ a (u ++ v) = occ a u + occ a v := by induction 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? := by induction 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 := by induction w with | nil => simp [bigram, occ] | cons a w ih => simp only [bigram, occ] unfold hit split <;> split <;> split <;> simp_all <;> omega theorem in_bound (x z y : Nat) (hxz : x ≠ z) (w : Word) : bigram x y w + bigram z y w ≤ occ y w.tail := by induction 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 ih simp only [occ] unfold hit split <;> split <;> split <;> simp_all <;> omega theorem tail_occ_le (a : Nat) (w : Word) : occ a w.tail ≤ occ a w := by cases w <;> simp [occ] def Factor (u w : Word) : Prop := ∃ l t, w = l ++ u ++ t theorem factor_pos (x y : Nat) {u w : Word} (hu : Factor u w) (h : 0 < bigram x y u) : 0 < bigram x y w := by obtain ⟨l,t,rfl⟩ := hu rw [bigram_append, bigram_append] omega def privatePhase (p q : Word) := p ++ p ++ q ++ p ++ q ++ q private 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 := by have pn : p ≠ [] := by intro e; simp [e] at hp have qn : q ≠ [] := by intro e; simp [e] at hq refine ⟨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] <;> omega private 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 := by obtain ⟨hsi,hsj,hti,htj⟩ := private_boundaries hf hp hq ep eq have outs (a : Nat) (hai : 0 < bigram a i w) (haj : 0 < bigram a j w) : x ≠ a := by intro h; subst a by_cases hy : y = i · subst y have b := out_bound x i j hij w have c := hc x unfold Link at hxy omega · have b := out_bound x y i hy w have c := hc x unfold Link at hxy omega have ins (a : Nat) (hsa : 0 < bigram s a w) (hta : 0 < bigram t a w) : y ≠ a := by intro h; subst a by_cases hx : x = s · subst x have b := in_bound s t y hst w have c := hc y have d := tail_occ_le y w unfold Link at hxy omega · have b := in_bound x s y hx w have c := hc y have d := tail_occ_le y w unfold Link at hxy omega exact ⟨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) := by obtain ⟨xs,xt,yi,yj⟩ := h simp only [bigram_append, List.getLast?_append, ep, eq, hp, hq] simp [hit, Ne.symm xs, Ne.symm xt, Ne.symm yi, Ne.symm yj] omega theorem 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 := by have hd : cap r (l ++ q ++ p ++ u) := by intro a have b := hc a simp only [occ_append] at b ⊢ omega constructor · intro h have good := safe_ends hc hf hp hq ep eq hij hst h exact (safe_count_swap l u hp hq ep eq good).symm.trans h · intro h have good := safe_ends hd hg hp hq ep eq hij hst h exact (safe_count_swap l u hp hq ep eq good).trans h /-- Nonoriented finite paths generate the repeated-block partition on saturated 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 z def SameBlock (r : Nat) (w : Word) (x y : Nat) : Prop := occ x w = r ∧ occ y w = r ∧ Joined (Link r w) x y theorem 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 := by have 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 remains a link of a capped enclosing word. To pull a block distinction back from 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 := by have bound := out_bound x y (y+1) (by omega) w have ceil := hc x obtain ⟨l,t,rfl⟩ := f unfold Link at * rw [bigram_append, bigram_append] at bound ⊢ omega private 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 := by induction 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 := by obtain ⟨hx,hy,hj⟩ := h refine ⟨?_,?_,joined_of_imp (fun _ _ hh => link_factor f hc hh) hj⟩ all_goals obtain ⟨l,t,rfl⟩ := f have bx := hc x have by' := hc y simp only [occ_append] at bx by' ⊢ omega end Problem455Swap end /- Begin Problem455DonorInterval (from finite-semigroup-identity-bases). -/ section namespace P455DonorInterval universe u v variable {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] /-- Count the contributions of one chosen donor and all other variables separately, 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 := by induction w with | nil => simp | cons a w ih => by_cases e : a = x · subst a simp [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 is contributed exactly once per occurrence, and by no other variable present 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 := by have spl := split_contributions h w x s rw [hx] at spl have pos := List.count_pos_iff.mpr mem have one : (h x).count s = 1 := by apply Classical.byContradiction intro diff have two : 2 ≤ (h x).count s := by omega have ge := Nat.mul_le_mul_left r two rw [Nat.mul_two] at ge omega rw [one,Nat.mul_one] at spl have 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_y apply none exact 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 numbers for 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 := by induction 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)) eq simp [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 := by have hr : 0 < r := by rw [← 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 bounded have single' := single simp 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 noOther have 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 noOther exact ⟨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, some literal name of the open source slot supplies it. No global condition on 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 := by have nowhere := other simp only [image,List.mem_append,List.mem_singleton,not_or] at nowhere simp only [List.mem_append] at occupies rcases 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, every copy of s occurs in that factor. In particular external context cannot change 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 := by simp only [List.count_append,saturated] at capped exact ⟨List.count_eq_zero.mp (by omega),List.count_eq_zero.mp (by omega)⟩ end P455DonorInterval end /- Begin Problem455MathlibCode (from finite-semigroup-identity-bases). -/ section namespace P455MathlibCode open Turing Turing.PartrecToTM2 def pos : List Bool → PosNum | [] => .one | true :: xs => .bit1 (pos xs) | false :: xs => .bit0 (pos xs) def wire (xs : List Bool) : Nat := pos xs.reverse def letter : Bool → Γ' | false => .bit0 | true => .bit1 theorem trPos (xs : List Bool) : trPosNum (pos xs) = xs.map letter ++ [.bit1] := by induction 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 := by simp [wire,trNat,PosNum.of_to_nat,trNum,trPos,← List.map_reverse] theorem pos_injective : Function.Injective pos := by intro xs induction 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 h theorem wire_injective : Function.Injective wire := by intro x y h have hn := congrArg (fun n : Nat => (n : Num)) h simp only [wire,PosNum.of_to_nat,Num.pos.injEq] at hn simpa using congrArg List.reverse (pos_injective hn) def op (b : Bool) (n : Nat) := if b = true then (n+n)+1 else n+n theorem pos_fold (xs : List Bool) : (pos xs : Nat) = xs.foldr op 1 := by induction 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 := by have h : Primrec (fun z : Bool × Nat => op z.1 z.2) := by exact 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_eq fun xs => (pos_fold xs.reverse).symm def 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 none theorem check_prim : Primrec₂ check := by have 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)) := by have 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 d obtain ⟨n, hn⟩ := Nat.rfindOpt_spec h unfold check at hn split at hn next ht => exact Eq.mp (congrArg (fun b => b ∈ Nat.rfindOpt (check (wire x))) ((Option.some.inj hn).symm.trans (wire_injective ht))) h next => 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] := by let 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 P455MathlibCode end /- Begin Problem455MathlibMarker (from finite-semigroup-identity-bases). -/ section namespace P455MathlibMarker open Turing variable {K : Type} {G : K → Type} {L V : Type} [DecidableEq K] abbrev Track := TM2to1.Γ' K G def 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 => True omit [DecidableEq K] in theorem trNormal_safe (s : TM2.Stmt G L V) : safe (TM2to1.trNormal s) := by induction s <;> simp_all [TM2to1.trNormal,safe] theorem tr_safe (M : L → TM2.Stmt G L V) (q) : safe (TM2to1.tr M q) := by cases 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 p def preserves (a : Track (G := G)) : TM0.Stmt (Track (G := G)) → Prop | .move _ => True | .write b => b.1=a.1 variable (hm : ∀ l, safe (M l)) include hm omit [DecidableEq K] [Inhabited L] [Inhabited V] in theorem 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 := by induction 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] in theorem 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 := by classical refine ⟨S.filter (safeState M), ⟨?_,?_⟩,?_⟩ · apply Finset.mem_filter.mpr refine ⟨hs.1, ?_⟩ intro p hp change some (M default) = some p at hp exact (Option.some.inj hp) ▸ hm default · rintro ⟨_ | p,v⟩ a q' s step good · contradiction obtain ⟨mem,safeP⟩ := Finset.mem_filter.mp good have hp := safeP p rfl have h := (trAux_safe M hm a p hp v).1 exact 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 · contradiction have hp := (Finset.mem_filter.mp good).2 p rfl have h := (trAux_safe M hm a p hp v).2 exact (congrArg (preserves a) (congrArg Prod.snd (Option.some.inj step))).mp h end P455MathlibMarker end /- 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.Move open Problem455 variable {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 := by obtain ⟨f,bit,l,t,hf,hu,hv,hc⟩ := h have hr := hf.1 have hx : ∀ x, x ∈ f.p ∨ x ∈ f.q → (l ++ f.early ++ f.mid ++ f.beforeMutable).count x = r-2 := by intro x hx have hh := f.mutable_index hf bit l t (hu ▸ hc) x hx omega obtain ⟨_,_,_,np,nq,dis,marks,_⟩ := hf let s : Slots.Move (r-2) := { pre := l ++ f.early ++ f.mid ++ f.beforeMutable p := f.p q := f.q post := f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q ++ t dp := np dq := nq disjoint := dis indexP := 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.pre p := s.q q := s.p post := s.post dp := s.dq dq := s.dp disjoint := fun x hx hx' => s.disjoint x hx' hx indexP := s.indexQ indexQ := 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 := by obtain ⟨s,rfl,rfl,_⟩ := asSlotMove h exact Slots.immutable_pattern s pat idx theorem 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 := by obtain ⟨s,rfl,rfl,_,hr⟩ := asSlotMove h have h1 : i ≠ r-2 := by unfold Slots.slotStart at hi; omega have h2 : i+1 ≠ r-2 := by unfold Slots.slotStart at hi; omega exact 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 := by obtain ⟨s,rfl,rfl,marks,_⟩ := asSlotMove h apply Slots.protected_projection by_cases hap : a ∈ s.p · right intro x hx simp 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 · right intro x hx simp 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)⟩ · left intro x hx simp 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 := by constructor · obtain ⟨s,rfl,rfl,_⟩ := asSlotMove h exact Slots.type_forward s a b tag hne (by omega) · obtain ⟨s,hu,hv,_⟩ := asSlotMove h.symm rw [hu,hv] exact Slots.type_forward s a b tag hne (by omega) end P455Closure.Move end /- Begin Problem455Finite (from finite-semigroup-identity-bases). -/ section namespace Problem455Finite def rules (r : Nat) (allow : List Bool → Prop) (mark : Nat → Nat → Prop) : P455Quotient.Rules Nat where r := r step := P455Closure.Move r allow mark reverse := P455Closure.Move.symm counts := P455Closure.Move.count_eq extend h l t := P455Closure.Move.extend_of_cap h l t open 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 := by induction 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 len have hw := ih w hl (fun z hz => names z (by simp [hz])) apply List.mem_cons_of_mem apply List.mem_flatMap.mpr exact ⟨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 := by obtain ⟨v,path,l,t,hv⟩ := good have perm := List.perm_iff_count.mpr (count_walk R path) have len := perm.length_eq refine ⟨?_,?_⟩ · simp only [hv,List.length_append] at len omega · intro x hx apply perm.mem_iff.mpr simp [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 := by by_cases dead : q = zero R T · simp [carrier,dead] · obtain ⟨w,good,e⟩ := nonzero_representative R q dead obtain ⟨len,names⟩ := good_bound R T w good exact List.mem_cons_of_mem _ (List.mem_map.mpr ⟨w, covered T T.length w len names, e⟩) end Problem455Finite end /- Begin Problem455BlockBridge (from finite-semigroup-identity-bases). -/ section namespace Problem455BlockBridge open P455Closure open Problem455Swap theorem occ_count (a : Nat) (w : List Nat) : occ a w = w.count a := by induction 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.beforeMutable private def rightPart (f : Frame Nat) (t : List Nat) := f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q ++ t private 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 := by simp [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 := by simp [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) := by refine ⟨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 := by have pn : f.p ≠ [] := by simp [Frame.p] have qn : f.q ≠ [] := by simp [Frame.q] let i := f.pHead let j := f.q.head qn let s := f.p.getLast pn let z := f.qLast have hp : f.p.head? = some i := rfl have hq : f.q.head? = some j := List.head?_eq_head qn have ep : f.p.getLast? = some s := List.getLast?_eq_getLast pn have eq : f.q.getLast? = some z := by simp [Frame.q,z] have disj := wf.2.2.2.2.2.1 have 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) := by intro a rw [occ_count] exact hc a have ef := early_factor f l t false have et := early_factor f l t true rw [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 := by have hd := h.cap_right obtain ⟨f,b,l,t,hf,rfl,rfl,hc⟩ := h cases 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 paths in 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 := by have 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 Problem455BlockBridge end /- Begin Problem455MathlibTM (from finite-semigroup-identity-bases). -/ section /- The compilation fixes a finite machine before the input. Its exact terminal tape equals the same physical encoding of the output list. -/ namespace P455MathlibTM open Turing PartrecToTM2 P455MathlibCode abbrev 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 := by unfold TM2to1.trInit rw [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 := by cases ha with | mk t ht => cases hb with | mk s hs => have eq : t=s := by apply ListBlank.ext intro n funext k have h := congrArg (fun z => ListBlank.nth z n) ((ht k).trans (hs k).symm) simpa only [proj_map_nth] using h subst s rfl private 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⟩ := by cases h with | mk t ht => exact .mk t ht private theorem stack_update (x : List Γ') : Function.update (fun _ : K' => ([] : List Γ')) .main x = K'.elim x [] [] [] := by funext k cases k <;> simp [K'.elim,Function.update] /-- Finiteness of the actual alphabet, a finite support of reachable control 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)) := by classical obtain ⟨c, hc⟩ := compile hf letI : Inhabited PartrecToTM2.Λ' := ⟨trNormal c .halt⟩ let M₁ := TM2to1.tr PartrecToTM2.tr let 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 x let v := [wire x] let w := [wire (f x)] have run : PartrecToTM2.halt w ∈ StateTransition.eval (TM2.step PartrecToTM2.tr) (PartrecToTM2.init c v) := by rw [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) := by simp [PartrecToTM2.init,TM2.init,stack_update] rfl rw [e] at run obtain ⟨b, hb, rb⟩ := StateTransition.tr_eval (TM2to1.tr_respects PartrecToTM2.tr) (TM2to1.trCfg_init (Γ := fun _ : K' => Γ') (Λ := PartrecToTM2.Λ') (σ := Option Γ') K'.main (trList v)) run have 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 target have eq := unique_sim hb target subst b obtain ⟨d, hd, rd⟩ := StateTransition.tr_eval (TM1to0.tr_respects M₁) rfl rb subst d refine ⟨(none,none),?_⟩ dsimp only [v,w] at rd rw [tr_input, tr_input] at rd change (⟨(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 rd end P455MathlibTM end /- Begin Problem455FactorSlots (from finite-semigroup-identity-bases). -/ section namespace Problem455.Slots def 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) := by induction 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 := by induction 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 := by rw [← labels_of_stamp n w] exact List.mem_map_of_mem h theorem 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) := by have 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) f simp only [Nat.add_zero] at hh simp only [List.append_assoc, events, stamp_append, hn, hh] rfl private theorem trim_left {α : Type} {a : α} {pat u v : List α} (ha : a ∉ u) (h : (a :: pat).Sublist (u ++ v)) : (a :: pat).Sublist v := by induction 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 := by constructor · intro h have h' := (trim_left ha h).reverse simp 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').reverse simpa using hh · intro h exact List.sublist_append_of_sublist_right (List.sublist_append_of_sublist_left h) /-- No assumption on the number of outside copies of the occupant. Its occurrence 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 := by have hz := List.count_eq_zero.mpr hl have 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 x have 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 h rw [events_of_factor] at h have 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 sees rw [events_of_factor] apply (trim_three left right).mpr have 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 the underlying 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 := by have h := cap owner simp only [List.count_append, sat] at h exact 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 := by have fresh : ∀ e ∈ pat, l.count e.1 = 0 ∧ e.1 ∉ t := by intro e he have hh := cap e.1 simp only [List.count_append, sat e he] at hh exact ⟨by omega,List.count_eq_zero.mp (by omega)⟩ let n := fun x => l.count x have 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 := by conv => rhs; rw [← List.map_id (l := pat)] apply List.map_congr_left intro e he simp [shift,n,(fresh e he).1] have hr : pat.map (unshift n) = pat := by conv => rhs; rw [← List.map_id (l := pat)] apply List.map_congr_left intro e he simp [unshift,n,(fresh e he).1] unfold sees rw [events_of_factor] constructor · intro h have mid := (h.of_sublist_append_right left).of_sublist_append_left right have hh := mid.map (unshift n) simpa [hr, List.map_map, Function.comp_def, Nat.add_sub_cancel_left, unshift, shift, n] using hh · intro h have hh := h.map (shift n) rw [hs] at hh exact List.sublist_append_of_sublist_right (List.sublist_append_of_sublist_left hh) /- If an occupant is not saturated, its occurrence number can change even when the owner is saturated. Here 3 is the owner and the leading 7 is outside the factor. These closed examples are separate from the lemmas. -/ example : sees [3,7,3] [(3,0),(7,0),(3,1)] := by unfold sees; decide example : ¬ sees [7,3,7,3] [(3,0),(7,0),(3,1)] := by unfold sees; decide example : sees [7,3,7,3] [(3,0),(7,1),(3,1)] := by unfold sees; decide end Problem455.Slots end /- Begin Problem455Uncrossed (from finite-semigroup-identity-bases). -/ section namespace P455Uncrossed open P455Closure Problem455Finite abbrev W := List Nat abbrev Tags := List Bool → Prop abbrev Marks := Nat → Nat → Prop def side (f : Frame Nat) (l k : W) (bit : Bool) := l ++ f.core bit ++ k def Unmarked (mark : Marks) (h : Nat → W) (x y : Nat) : Prop := ∀ a ∈ h x, ∀ b ∈ h y, ¬ mark a b ∧ ¬ mark b a private theorem nodup_of_counts (w : W) (h : ∀ a ∈ w, w.count a ≤ 1) : w.Nodup := by induction w with | nil => simp | cons a w ih => apply List.nodup_cons.mpr have one := h a (by simp) simp only [List.count_cons_self] at one exact ⟨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 := by have base := valid.2.2.2.2.2.2.2 a mem cases bit · exact base · exact (f.count_core a true).trans base private def mappedFrame (f : Frame Nat) (h : Nat → W) (pHead : Nat) (pTail qInit : W) (qLast : Nat) : Frame Nat where pHead := pHead pTail := pTail qInit := qInit qLast := qLast tag := f.tag middle := f.middle.map (fun e => (e.1.flatMap h, e.2)) beforeMutable := f.beforeMutable.flatMap h beforeFinalP := f.beforeFinalP.flatMap h beforeFinalQ := f.beforeFinalQ.flatMap h private 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 := by simp only [Frame.mid,mappedFrame,List.flatMap_assoc,List.flatMap_map] congr 1 funext z obtain ⟨w,b⟩ := z cases b <;> simp only [Function.comp_apply, Bool.false_eq_true, if_false, if_true, List.flatMap_append, hp, hq] <;> rfl private 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 := by have mid := mid_image f h phead pt qi qlast hp hq cases bit <;> simp only [Frame.core,Frame.early,Frame.pair,Bool.false_eq_true,if_false,if_true, List.flatMap_append, mid, hp, hq] <;> rfl theorem 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) := by have 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 = [] · left rcases empty with hx | hy <;> cases bit <;> simp [side,Frame.core,Frame.pair,List.flatMap_append,xmap,ymap, *] right have 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_all obtain ⟨qi,qlast,q⟩ : ∃ t a, h y = t ++ [a] := by cases 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 qlast have gp : g.p = h x := p.symm have gq : g.q = h y := q.symm have eq (b : Bool) : (side f l k b).flatMap h = l.flatMap h ++ g.core b ++ k.flatMap h := by simp 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) := by intro a; have hh := cap a; simp only [side,List.flatMap_append,List.count_append] at hh; omega have 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; omega have 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 ▸ cap have gv : g.Valid r allow mark := by apply 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_counts exact fun a ha => Nat.le_of_eq (excl a ha).1 · rw [gq]; apply nodup_of_counts exact 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 clear exact ⟨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) := by let R := rules r allow mark have cap := P455Quotient.good_cap R capT good rcases 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 _) move have equiv := P455Quotient.good_context R capT path [] [] simp only [List.nil_append,List.append_nil] at equiv exact (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) := by let R := rules r allow mark by_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 g by_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').symm have dead (w : W) (h : ¬ P455Quotient.Good R T w) : P455Quotient.ofWord R T w = P455Quotient.zero R T := by apply Classical.byContradiction intro nz; exact h ((P455Quotient.nonzero_iff R).mp nz) exact (dead _ g).trans (dead _ g').symm theorem same_letters (f : Frame Nat) (l k : W) (bit : Bool) (a : Nat) : a ∈ side f l k bit ↔ a ∈ side f l k (!bit) := by have c := f.count_core a bit have perm : (side f l k bit).count a = (side f l k (!bit)).count a := by simp only [side,List.count_append,c] rw [←List.count_pos_iff,←List.count_pos_iff,perm] /-- Arbitrarily chosen quotient representatives for all occurring variables are 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)) := by rw [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 of representatives 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 := by apply Classical.byContradiction intro none apply diff apply uncrossed_eval capT f l k bit x y hp hq valid val h reps intro a ha b hb exact ⟨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 arbitrary good-word representatives for its letters. Each such simultaneous choice occurs 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) := by classical let R := rules r allow mark have live : ∃ bit, P455Quotient.eval R capT val (side f l k bit) ≠ P455Quotient.zero R T := by by_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⟩ := live refine ⟨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 reps exact (P455Quotient.arbitrary_representatives R capT val _ h reps).mp nz end P455Uncrossed end /- Begin Problem455EffectiveQReach (from finite-semigroup-identity-bases). -/ section namespace P455EffectiveQReach open P455Quotient variable {α : 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 := by induction 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 := by induction 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 := by induction s generalizing a b with | nil => simp only [via,Bool.or_eq_true,decide_eq_true_eq] at h rcases 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 h exact 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 := by induction p with | refl => exact initial _ _ (.inl rfl) | snoc p step ih => exact splice _ _ (cover _ p) ih (initial _ _ (.inr (ok _ _ step))) end P455EffectiveQReach end /- Begin Problem455Witness (from finite-semigroup-identity-bases). -/ section namespace P455Witness open Problem455.Slots abbrev W := List Nat abbrev Tag := List Bool abbrev 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 y theorem 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 := by rcases hm with forward | reverse · exact h.marked_proj a b forward · simpa only [select_pair_symm b a] using h.marked_proj b a reverse theorem 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 := by induction 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 jh def 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 True structure Node where owner : Nat mate : Nat tag : Tag deriving DecidableEq def typedNode (n : Node) := Query.record n.owner n.mate n.tag def markedNode (n : Node) (b : Bool) := Query.markedBit n.owner n.mate n.tag b def 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 role on 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.val let x := if rev then b else a let y := if rev then a else b allQ [.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 where anchor : Node bit : Bool startAtMate : Bool steps : List (Nat × ContactChoice) terminalIndex : Nat defect : SlotDefect def SlotCertificate.query (s : SlotCertificate) (r : Nat) : Query := let start := if s.startAtMate then s.anchor.mate else s.anchor.owner allQ [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 where horizontal : Tag → Tag → Prop vertical : Tag → Tag → Prop left : Tag → Bool right : Tag → Bool top : Tag → Bool bottom : Tag → Bool oddColumn : Tag → Bool oddRow : Tag → Bool def orientedPort (phase : Nat) (a b : Node) : Query := let i := 3 + 2 * phase let x := a.owner; let y := a.mate; let z := b.owner; let t := b.mate allQ [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 | up def 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 a structure FunctionalityCertificate where anchor : Node bit : Bool b : Node c : Node dir : Dir distinguishMate : Bool def FunctionalityCertificate.query (f : FunctionalityCertificate) (ts : Tiles) := let role := fun n : Node => if f.distinguishMate then n.mate else n.owner allQ [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 where a : Node b : Node right : Node left : Node down : Node up : Node diagonal : Node def endOfRow (ts : Tiles) (a : Node) := if ts.oddRow a.tag then ts.left a.tag else ts.right a.tag def localCert (ts : Tiles) (e : EdgeCertificate) := let a := e.a allQ [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.b if endOfRow ts a && ts.bottom a.tag then allQ [.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] else let 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 ts abbrev rules := Problem455Finite.rules /-- Every enclosing variant keeps the same designated certificate, even when a 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) := by intro h exact 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) := by apply P455Quotient.designated (rules r allow mark) cap val v h reps live _ initial exact fun mv old => (query_invariant mv _).mp old end P455Witness end /- Begin Problem455SameDonor (from finite-semigroup-identity-bases). -/ section namespace Problem455SameDonor open Problem455Swap private 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) := by have pos : 0 < occ a (h x) := by rw [Problem455BlockBridge.occ_count] exact List.count_pos_iff.mpr ha induction 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]; omega private 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) := by induction 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]; omega private theorem transJoined {e : Nat → Nat → Prop} {a b c : Nat} (h1 : Joined e a b) (h2 : Joined e b c) : Joined e a c := by induction h2 with | refl => exact h1 | extend _ z ih => exact .extend ih z private theorem symmJoined {e : Nat → Nat → Prop} {a b : Nat} (h : Joined e a b) : Joined e b a := by induction h with | refl => exact .refl _ | extend _ z ih => exact transJoined (.extend (.refl _) z.symm) ih private 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 := by induction t generalizing a with | nil => intro b hb have := List.mem_singleton.mp hb subst b; exact .refl _ | cons c t ih => intro b hb rcases 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 := by intro i j pos apply links change 0 < hit i j (some a) (some c) + bigram i j (c :: t) omega exact transJoined (.extend (.refl _) (.inl ac)) (ih c tailLinks b hb) /-- Under the cap, every label in the image of an r-occurring source variable is 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 := by have cap' : cap r (v.flatMap h) := by intro j; rw [Problem455BlockBridge.occ_count]; exact hc j have sat (i : Nat) (hi : i ∈ h x) : occ i (v.flatMap h) = r := by have lower := count_le_output h x i hi v have upper := cap' i omega have links (i j : Nat) (ij : 0 < bigram i j (h x)) : Link r (v.flatMap h) i j := by have lower := count_le_edge h x i j ij v have upper := out_bound i j (j+1) (by omega) (v.flatMap h) have ceiling := cap' i unfold Link omega refine ⟨sat a ha,sat b hb,?_⟩ cases eq : h x with | nil => simp [eq] at ha | cons c t => rw [eq] at ha hb links exact 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 := by induction v with | nil => simp | cons b v ih => simp only [List.flatMap_cons, List.count_append] by_cases e : b = x · subst b simp [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 other variable USED by v donates that letter. Variables absent from v are legitimately 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 := by constructor · have m := multiplicity_lower v h x a rw [hx] at m have p := List.count_pos_iff.mpr ha have c := hc a by_cases hn : (h x).count a = 1 · exact hn · exfalso have two : 2 ≤ (h x).count a := by omega have bad := Nat.mul_le_mul_left r two omega · intro y hy yx ay obtain ⟨l,t,e⟩ := List.append_of_mem hy have h1 := count_le_output h x a ha l have h2 := count_le_output h x a ha t rw [Problem455BlockBridge.occ_count] at h1 h2 have yPos := List.count_pos_iff.mpr ay have c := hc a simp only [e,List.flatMap_append,List.flatMap_cons,List.count_append] at c simp [e,List.count_append,List.count_cons,yx] at hx omega end Problem455SameDonor end /- Begin Problem455MathlibFinite (from finite-semigroup-identity-bases). -/ section namespace P455MathlibFinite open Turing P455MathlibTM /-- The states really form a finite type. Every instruction writing on the 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)) := by classical obtain ⟨L,I,M,S,hs,guard,run⟩ := supported hf let Q := {q : L // q ∈ S} letI : Inhabited Q := ⟨⟨default,hs.1⟩⟩ let pick (q : L) : Q := if h : q ∈ S then ⟨q,h⟩ else default have 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.val refine ⟨Q,inferInstance,inferInstance,N,?_,?_⟩ · intro q a q' b step change (M q.val a).map (Prod.map pick (TM0.Stmt.map sym)) = _ at step obtain ⟨⟨r,s⟩,hr,he⟩ := Option.map_eq_some_iff.mp step cases s with | move d => change (pick r, TM0.Stmt.move d) = (q',TM0.Stmt.write b) at he cases he | write z => change (pick r,TM0.Stmt.write z) = (q',TM0.Stmt.write b) at he have eq : z=b := TM0.Stmt.write.inj (congrArg Prod.snd he) exact eq ▸ guard q.val q.property a r z hr · intro x obtain ⟨r,stop⟩ := run x have sim := TM0.Machine.map_respects M sym sym (⟨pick,Subtype.ext (proj _ hs.1)⟩ : PointedMap L Q) Subtype.val hs (fun _ => rfl) proj have lift (q : L) (xs : List Track) : TM0.Cfg.map sym pick (⟨q,Tape.mk₁ xs⟩ : TM0.Cfg Track L) = ⟨pick q,Tape.mk₁ xs⟩ := by simp [TM0.Cfg.map,Tape.map_mk₁,sym] have eq : TM0.Cfg.map sym pick (TM0.init (Λ := L) (image x)) = TM0.init (Λ := Q) (image x) := by unfold TM0.init rw [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⟩ stop subst b rw [lift] at ok exact ⟨_,ok⟩ end P455MathlibFinite end /- Begin Problem455SlotOrigin (from finite-semigroup-identity-bases). -/ section namespace P455SlotOrigin open Problem455.Slots theorem 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 := by induction 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 he simp [List.count_cons] · have h := ih (advance n [b]) he simp 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 := by induction w generalizing i with | nil => simp at hi | cons a w ih => by_cases h : a = x · subst a cases i with | zero => exact ⟨[],w,rfl,rfl⟩ | succ i => have c : i < w.count x := by simpa [List.count_cons] using hi obtain ⟨l,t,e,ei⟩ := ih i c exact ⟨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 hi obtain ⟨l,t,e,ei⟩ := ih i c exact ⟨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 := by obtain ⟨l,suffix,e,ei⟩ := occurrence_cut w x i (by omega) have hs : x ∈ suffix := by apply List.count_pos_iff.mp rw [e,List.count_append,ei] at hi simp only [List.count_cons_self] at hi omega obtain ⟨mid,t,et,hn⟩ := List.eq_append_cons_of_mem hs exact ⟨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 := by induction 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)).elim private 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 := by constructor · intro sub rw [List.append_assoc] at sub have inner := (trim_start a _ l _ ha sub).reverse simp only [List.reverse_append,List.reverse_cons,List.reverse_nil, List.append_nil,List.nil_append,List.singleton_append,List.cons_append] at inner rw [List.append_assoc] at inner have back := (trim_start b _ t.reverse _ (by simpa using hb) inner).reverse have mid : [a,y,b].Sublist (a :: (m ++ [b])) := by simpa using back have last : ([y] ++ [b]).Sublist (m ++ [b]) := List.cons_sublist_cons.mp mid simpa using (List.append_sublist_append_right [b]).mp last · intro hy have sub : ([y] : List α).Sublist m := by simpa using hy have sub₂ := (List.append_sublist_append_right [b]).mpr sub exact 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 deficient occupant. 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 := by let 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 := by simp [n,advance,List.count_append,List.count_eq_zero.mpr hn] have ne : n' x = l.count x+2 := by simp [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 := by unfold events simp 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 := by intro h have hh := (event_bounds (fun _ => 0) l x _ h).2 omega have hb : (x,l.count x+1) ∉ stamp n' t := by intro h have hh := (event_bounds n' t x _ h).1 omega unfold occupies sees rw [eq] constructor · rintro ⟨j,hj⟩ exact stamped_mem_label n mid (y,j) ((framed_iff _ _ _ _ _ _ ha hb).mp hj) · intro hy rw [← labels_of_stamp n mid] at hy obtain ⟨⟨a,j⟩,he,rfl⟩ := List.mem_map.mp hy exact ⟨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 := by have cb : (v.flatMap h).count s ≤ r := by have c := cap s simp only [List.count_append] at c omega have sat := (P455DonorInterval.exclusive h v x s r hr hx hs cb).2.2 have hf := (saturated_factor_occupies l (v.flatMap h) k s i t r cap sat).mp ho have bound : i+1 < v.count x := by obtain ⟨j,hj⟩ := hf have he : (s,i+1) ∈ events (v.flatMap h) := hj.mem (by simp) have hh := (event_bounds (fun _ => 0) _ s _ he).2 omega obtain ⟨L,I,R,cut,idx,cons⟩ := slot_cut v x i bound obtain ⟨p,q,split,_⟩ := List.eq_append_cons_of_mem hs have image : h x = p ++ [s] ++ q := by simpa [List.append_assoc] using split obtain ⟨_,_,_,hni,hw,hi,_⟩ := P455DonorInterval.consecutive_interval h v L I R x s p q r cut cons image hx cb have hit : t ∈ q ++ I.flatMap h ++ p := by rw [← idx, ← hi, hw] at hf exact (occupies_at_cut _ _ _ _ _ hni).mp hf obtain ⟨y,hy,don⟩ := P455DonorInterval.interior_supplier h I x s t p q image hit hout have occ : occupies v x i y := by rw [cut,← idx] exact (occupies_at_cut _ _ _ _ _ cons).mpr hy exact ⟨y,occ,don,guard y occ,fun eq => hout (eq ▸ don)⟩ /-- A terminal slot may include the boundary donor. No contact or separate-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 := by by_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 P455SlotOrigin end /- Begin Problem455EffectiveQ (from finite-semigroup-identity-bases). -/ section namespace P455EffectiveQ open P455Quotient Problem455Finite abbrev W := List Nat def words (u : W) := wordsUpTo u u.length theorem subword {u v : W} (s : u.Sublist v) : u ∈ words v := covered v v.length u s.length_le s.subset def 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 := by simp 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 v theorem 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 := by constructor · exact P455EffectiveQReach.sound _ (fun x y => (ok x y).mp) _ · intro path apply P455EffectiveQReach.complete _ (fun x y => (ok x y).mpr) _ _ path intro x reach have 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 v theorem 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 := by simp 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 u def 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 | _,_ => false def relB (e : W → W → Bool) (T : W) (a b : Raw Nat) := ((!liveB e T a) && (!liveB e T b)) || paired e T a b theorem 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 := by have live (x : Raw Nat) : liveB e T x=true ↔ Live R T x := by cases x with | none => simp [liveB,Live] | some u => exact good_iff R e ok T u have no (x : Raw Nat) : (!liveB e T x)=true ↔ ¬Live R T x := by rw [←live]; cases liveB e T x <;> decide simp only [relB,Bool.or_eq_true,Bool.and_eq_true,no,P455Quotient.Rel] apply or_congr_right cases 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) (by intro a b c d ac bd apply Bool.eq_iff_iff.mpr rw [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 := by induction 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 P455EffectiveQ end /- Begin Problem455PaddedTiles (from finite-semigroup-identity-bases). -/ section namespace P455PaddedTiles open P455Witness structure Tile (n : Nat) where left : Bool right : Bool top : Bool bottom : Bool oddRow : Bool oddColumn : Bool l : Option (Fin n) c : Fin n r : Option (Fin n) b : Fin n deriving DecidableEq def digit (n k : Nat) : Tag := List.replicate k true ++ List.replicate (n-k) false def letter : Option (Fin n) → Nat | none => 0 | some a => a.val+1 def 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 := by have lim : letter s ≤ n+1 := by cases s with | none => simp [letter] | some a => simp only [letter]; have := a.isLt; omega simp [token,digit]; omega theorem code_length (p : Tile n) : (code p).length = widthCode n := by simp [code,widthCode,token_length]; omega private theorem token_inj {a b : Option (Fin n)} (eq : token a = token b) : a=b := by have ct := congrArg (List.count true) eq have zero (k : Nat) : (List.replicate k false).count true=0 := by apply List.count_eq_zero.mpr intro m have := List.eq_of_mem_replicate m contradiction simp [token,digit,zero] at ct cases a <;> cases b <;> simp_all [letter,Fin.ext_iff] theorem code_inj {p q : Tile n} (eq : code p = code q) : p=q := by cases 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 eq obtain ⟨rfl,rfl,rfl,rfl,rfl,rfl,eq⟩ := eq obtain ⟨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) where marker : Fin n → Bool initial : Bool → Fin n accept : Fin n distinct : initial true ≠ accept next : 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 p def 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.c def 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.c def system (n : Nat) : Tiles where horizontal := fun x y => ∃ p q : Tile n, code p=x ∧ code q=y ∧ Horizontal p q vertical := fun x y => ∃ p q : Tile n, code p=x ∧ code q=y ∧ Vertical p q left := fun t => t[0]?.getD false right := fun t => t[1]?.getD false top := fun t => t[2]?.getD false bottom := fun t => t[3]?.getD false oddRow := fun t => t[4]?.getD false oddColumn := fun t => t[5]?.getD false def 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 update is checked once, including at both flagged boundaries. -/ structure Run (M : MachineTable n) (w s : Nat) where positive : 0 have z := (R.start 0 R.positive).symm.trans R.accept exact False.elim (M.distinct (by simpa using z)) | succ => omega def tileAt (R : Run M w s) (extra y x : Nat) : Tile n where left := decide (x=0) right := decide (x+1=w) top := decide (y=0) bottom := decide (y=s+extra) oddRow := odd y oddColumn := odd x l := leftAt (R.rows (min y s)) x c := R.rows (min y s) x r := rightAt (R.rows (min y s)) w x b := R.rows (min (y+1) s) x theorem admits_tile (R : Run M w s) (extra y x : Nat) (hx : x 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 b have ey : y=s+extra := of_decide_eq_true a have ex : x=0 := of_decide_eq_true b simpa [tileAt,ex,ey,Nat.min_eq_right (by omega : s≤s+extra)] using R.accept private theorem opposite (x : Nat) : odd x ≠ odd (x+1) := by unfold odd by_cases e : x%2=1 · have f : (x+1)%2 ≠ 1 := by omega simp [e,f] · have f : (x+1)%2 = 1 := by omega simp [e,f] theorem horizontal (R : Run M w s) (extra y x : Nat) (hx : x+1 code (tileAt R extra y x) eligible := fun y _ x hx => ⟨_,rfl,admits_tile R extra y x hx⟩ flags := by intro 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 every bound. Width one is allowed. The construction pads time alone. -/ theorem unbounded (R : Run M w s) (k : Nat) : ∃ h, 1 True | (b,c) :: rest => Holds r allow mark w (contact r s b c) ∧ Walk r allow mark w b rest def endpoint (s : Nat) : List Step → Nat | [] => s | (b,_) :: rest => endpoint b rest theorem 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)) := by induction 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 ≤ J theorem 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 := by obtain ⟨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 := by induction 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 := by induction p generalizing a with | nil => rfl | cons ab p ih => exact ih ab.1 theorem 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) := by obtain ⟨p,hp,ep,lp⟩ := h obtain ⟨q,hq,eq,lq⟩ := g exact ⟨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 w theorem allQ_iff {r allow mark w} (qs : List Query) : V r allow mark w (allQ qs) ↔ ∀ q ∈ qs, V r allow mark w q := by induction 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.owner s.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) := by simp only [SlotCertificate.query,allQ,Holds,V] at ok exact ⟨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 := by obtain ⟨ne,hl,_,bit,eq⟩ := recProof have n := congrArg List.length eq simp only [length_select_pair a b ne,profile,List.length_append,profile_prefix_length] at n have ca := bound a; have cb := bound b cases bit <;> simp [pair] at n <;> omega theorem 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 := by induction 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; omega theorem stamp_unique (n : Nat → Nat) (w : W) : (stamp n w).Nodup := by induction w generalizing n with | nil => simp [stamp] | cons a w ih => apply List.nodup_cons.mpr refine ⟨fun bad => ?_, ih _⟩ have low := stamp_lower (advance n [a]) w a (n a) bad simp [advance] at low <;> omega theorem 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]) := by rcases 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)) := by obtain ⟨na,nb,early,order,_⟩ := ok let i := 3 + 2*p.val let 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)] := by exact .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.2 have ne : a.owner ≠ b.owner := by intro eq have := (List.nodup_cons.mp nd).1 exact this (by simp [eq]) have xa := (record_counts cap na).1 have xb := (record_counts cap nb).1 have ed := owner_early a b early exact ⟨⟨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 1 theorem 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 := by obtain ⟨f,g⟩ := owner_port cap ⟨n,hn⟩ a b ok exact ⟨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.1 theorem 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.2 theorem 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 := by cases 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).symm theorem 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) := by cases 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.1 theorem 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 P455Paths end /- Begin Problem455ContactGeometry (from finite-semigroup-identity-bases). -/ section namespace P455ContactGeometry open 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)) := by induction 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 1 apply ih intro b hb simp [advance, agree b hb] · simp only [select, List.filter_cons, decide_eq_false ha, Bool.false_eq_true, if_false, stamp] apply ih intro b hb have 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) := by rw [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)) := by have shape : ∃ t : Word, profile a b tag bit = [a,a,b,a,b,b] ++ t := by unfold profile profilePrefix simp only [List.append_assoc] exact ⟨_,rfl⟩ obtain ⟨t,e⟩ := shape rw [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)] := by simp [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 that cannot 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)] := by obtain ⟨bit,eq⟩ := typ have initial := profile_initial ab tag bit rw [← eq] at initial have 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 from the 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)])) := by cases c with | record tag rev => cases rev · obtain ⟨ab,_,_,typ⟩ := hc obtain ⟨slot,_,ord⟩ := record_geometry ab typ exact ⟨⟨1,by simp [slotStart],slot⟩,⟨1,by decide,.inl ord⟩⟩ · obtain ⟨ba,_,_,typ⟩ := hc obtain ⟨_,slot,ord⟩ := record_geometry ba typ exact ⟨⟨0,by simp [slotStart],slot⟩,⟨1,by decide,.inr ord⟩⟩ | port phase rev => let i := 3+2*phase.val have hi : slotStart i := by have := phase.isLt; unfold i slotStart; omega have early : Holds r allow mark z (earlyDisjoint [a] [b]) := hc.2.2.2.1 have ord : sees z [(a,2),(b,0)] ∨ sees z [(b,2),(a,0)] := by rcases early with e | e · exact .inl e.1.2 · exact .inr e.1.2 refine ⟨⟨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.2 exact ⟨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.2 exact ⟨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 exclusive upper 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 := by induction 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 head simp [List.count_cons] · have z := ih _ tail by_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 ⊢; omega private 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)] := by intro e have h : [(a,i),(b,0)].Sublist (events f ++ stamp (advance (fun _ => 0) f) t) := by simpa only [sees, eq, events, stamp_append] using e have first : (a,i) ∉ events f := by intro mem have bad := (stamp_range (fun _ => 0) f mem).2 simp only [Nat.zero_add] at bad omega have last : (b,0) ∉ stamp (advance (fun _ => 0) f) t := by intro mem have := stamp_range (advance (fun _ => 0) f) t mem simp [advance] at this omega have strip {α : Type} {x y : α} {l k : List α} (n : x ∉ l) (s : [x,y].Sublist (l ++ k)) : [x,y].Sublist k := by induction 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)).elim exact 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 := by induction 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 in the 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)] := by have px : x ∈ v := List.count_pos_iff.mp (hx ▸ hr) obtain ⟨pre,post,cut,avoid⟩ := first_split x v px have bounds (j : Nat) (mem : j ∈ h x) : (l ++ pre.flatMap h ++ h x).count j = 1 := by have bb := bound j simp only [List.count_append] at bb obtain ⟨one,exclusive,sat⟩ := P455DonorInterval.exclusive h v x j r hr hx mem (by omega) have fresh : j ∉ pre.flatMap h := by intro z obtain ⟨y,hy,yj⟩ := List.mem_flatMap.mp z exact exclusive y (by simp [cut,hy]) (fun e => avoid (e ▸ hy)) yj have left : l.count j = 0 := by omega simp [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) := by simp [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 of h(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 := by intro hb obtain ⟨i,hi,ord⟩ := (geometry hc).2 rcases 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 ord end P455ContactGeometry end /- Begin Problem455ContactReflection (from finite-semigroup-identity-bases). -/ section namespace P455ContactReflection open Problem455.Slots P455Witness def 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) := by induction 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 1 apply ih intro b hb simp only [advance, eqn b hb] · simp only [stamp, select, List.filter_cons, ha, decide_false, Bool.false_eq_true, if_false] apply ih intro b hb have 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 := by have filtered := seen.filter (fun e => decide (e.1 ∈ keep)) have self : pat.filter (fun e => decide (e.1 ∈ keep)) = pat := by apply List.filter_eq_self.mpr; simpa using support rw [self] at filtered unfold sees events at * rw [select_stamped keep w _ (fun _ => 0) (fun _ _ => rfl)] at filtered exact filtered theorem select_sees (keep w : W) (pat : List Event) (seen : sees (select keep w) pat) : sees w pat := by unfold sees events at * rw [← select_stamped keep w (fun _ => 0) _ (fun _ _ => rfl)] at seen exact 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) := by induction 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 hb by_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 := by have 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 := by by_cases eq : x = d a · exact eq.symm · exact ((exclusive a ha).2.1 x hx eq in_h).elim have per (x) (hx : x ∈ v) : (select keep (h x)).map d = select (keep.map d) [x] := by by_cases mem : x ∈ keep.map d · obtain ⟨a,ha,eq⟩ := List.mem_map.mp mem have all_a (b) (hb : b ∈ select keep (h x)) : b = a := by obtain ⟨in_h,keep_b⟩ := List.mem_filter.mp hb have kb : b ∈ keep := by simpa using keep_b exact dinj b kb a ha ((owner x hx b kb in_h).trans eq.symm) have ct : (select keep (h x)).count a = 1 := by rw [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 := by induction 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)) := by have selected := sees_select keep _ pat inside seen apply 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 named exact named theorem 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 := by have bp (c : Bool) : (pair a b c).map d = pair (d a) (d b) c := by cases c <;> rfl have tp : (tag.flatMap (pair a b)).map d = tag.flatMap (pair (d a) (d b)) := by induction tag with | nil => rfl | cons c tag ih => simp [bp, ih] simp only [profile,profilePrefix,List.map_append,bp,tp] rfl private 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) := by have hy' : y ∈ v := List.count_pos_iff.mp (by omega) have diff : s ≠ t := by intro eq have 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 y have p : d s = x := by simp [d] have q : d t = y := by simp [d, Ne.symm diff] refine ⟨d,p,q,?_,?_⟩ · intro a mem simp only [List.mem_cons, List.not_mem_nil, or_false] at mem rcases mem with rfl | rfl · exact p.symm ▸ And.intro hx hs · exact q.symm ▸ And.intro hy ht · intro a ha b hb e simp only [List.mem_cons, List.not_mem_nil, or_false] at ha hb rcases ha with rfl | rfl <;> rcases hb with rfl | rfl <;> simp_all theorem 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 := by obtain ⟨d,p,q,uniform,inj⟩ := two_labels hr cap hx hy hxy hs ht have e := selected_donor_word hr cap [s,t] d uniform inj rw [eq,map_profile] at e simpa only [List.map_cons,List.map_nil,p,q] using e.symm theorem 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))) := by obtain ⟨imm, order⟩ := seen refine ⟨?_, reflect_order hr cap keep d uniform dinj pat inside order⟩ rintro e he obtain ⟨a,ha,rfl⟩ := List.mem_map.mp he exact imm a ha theorem 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) := by cases 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 ht have orders := @reflect_order_query r v l k h allow mark hr cap [s,t] d uniform inj have 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) := by have o := orders [(s,i),(t,j)] (by simp) sig simpa [eventMap,p,q,earlier] using o have 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) := by have o := orders [(t,i),(s,j)] (by simp) sig simpa [eventMap,p,q,earlier] using o intro core obtain ⟨_,_,_,early,ordered,_⟩ := core refine ⟨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.val cases rev with | false => have o := orders [(s,i),(t,i),(s,i+1),(t,i+1)] (by simp) ordered simpa [eventMap,p,q,i] using o | true => have o := orders [(t,i),(s,i),(t,i+1),(s,i+1)] (by simp) ordered simpa [eventMap,p,q,i] using o end P455ContactReflection end /- Begin Problem455TerminalTransfer (from finite-semigroup-identity-bases). -/ section namespace P455TerminalTransfer open Problem455.Slots P455Witness /-- In the overflow branch the assignment is specified only on the five selected 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) = r theorem holds_all {r allow mark z} (qs : List Query) : Holds r allow mark z (allQ qs) ↔ ∀ q ∈ qs, Holds r allow mark z q := by induction 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) := by induction 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 := by let z := l ++ v.flatMap h ++ k have capF : ∀ j, (v.flatMap h).count j ≤ r := by intro a have c := cap a simp only [List.count_append] at c omega have satZ (a y : Nat) (hy : v.count y = r) (ha : a ∈ h y) : z.count a = r := by have full := (P455DonorInterval.exclusive h v y a r hr hy ha (capF a)).2.2 have c := cap a simp only [z,List.count_append] at * omega have common (y a b : Nat) (hy : v.count y = r) (ha : a ∈ h y) (hb : b ∈ h y) : Problem455Swap.SameBlock r z a b := by have capZ : Problem455Swap.cap r z := by intro c rw [Problem455BlockBridge.occ_count] exact cap c exact 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⟩ := obs change z.count a < r at bad rcases P455SlotOrigin.supplier_or_boundary v h l k x s a i r hr cap hx hs occ guard with bnd | ⟨y,_,ay,hy,_⟩ · have := satZ a x hx bnd omega · have := satZ a y hy ay omega | overflow xs => change Holds r allow mark z (allQ _) at obs have ob := (holds_all _).mp obs have 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 sep have rest : ∀ a ∈ xs, occupies z s i a := by intro a ha have 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.2 classical have 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) guard let assign := fun a => if ha : a ∈ xs then (supply a ha).choose else x have spec (a : Nat) (ha : a ∈ xs) : occupies v x i (assign a) ∧ a ∈ h (assign a) ∧ v.count (assign a) = r ∧ x ≠ assign a := by simpa [assign,ha] using (supply a ha).choose_spec have nodup : (xs.map assign).Nodup := by apply List.pairwise_map.mpr apply tailSep.imp_of_mem intro a b ha hb distinct e have A := spec a ha have B := spec b hb exact 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 member obtain ⟨a,ha,e⟩ := List.mem_map.mp member exact (spec a ha).2.2.2 e.symm · intro a ha have e := spec a ha exact ⟨e.1,e.2.1,e.2.2.1⟩ end P455TerminalTransfer end /- Begin Problem455EffectiveQMove (from finite-semigroup-identity-bases). -/ section namespace P455EffectiveQMove open P455Closure P455EffectiveQ abbrev W := List Nat def 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 := by simp 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 a def 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 := by have unmarked (a b) : marks a b=false ↔ ¬mark a b := by rw [←mark_ok]; cases marks a b <;> decide simp 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) := by let u := l++f.core b++t have 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 core have 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 early have qq : f.q.Sublist u := (right (.refl _) : f.q.Sublist f.early).trans early have 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 := by have sz := congrArg List.length fv.2.2.1 apply Problem455Finite.covered _ _ _ (by simpa using Nat.le_of_eq sz) rintro ⟨g,v⟩ mem have item : g.Sublist f.mid := by let 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.mpr exact ⟨g,gg,by cases v <;> simp⟩ change f ∈ frames tags u simp 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 := by obtain ⟨f,b,l,t,valid,rfl,_,_⟩ := h have 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 := by cases b with | false => exact sat | true => exact (f.count_core f.pHead true).trans sat have len := List.count_le_length (a := f.pHead) (l := f.core b) simp only [List.length_append] omega def 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 := by simp 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 h have len := min_length h obtain ⟨f,b,l,t,fv,rfl,rfl,cp⟩ := h exact ⟨⟨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) T end P455EffectiveQMove end /- Begin Problem455RealizerGraph (from finite-semigroup-identity-bases). -/ section namespace P455RealizerGraph open P455EffectiveQ variable {α : 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) := by simp only [joinAt,List.mem_append,List.mem_flatMap] apply or_congr_right constructor · rintro ⟨⟨x,y⟩,px,h⟩ by_cases eq : y=k · subst y rw [if_pos rfl] at h obtain ⟨⟨z,w⟩,qz,h⟩ := List.mem_filterMap.mp h dsimp only at h split at h · rename_i hzk obtain ⟨hxa,hwb⟩ := Prod.mk.inj (Option.some.inj h) subst z; subst x; subst w exact ⟨px,qz⟩ · contradiction · simp [eq] at h · rintro ⟨p,q⟩ refine ⟨(a,k),p,?_⟩ simp [List.mem_filterMap] exact q def 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 := by simp 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 := by induction 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_self have 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 u decide ((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 := by apply Bool.eq_iff_iff.mpr simp only [walk,decide_eq_true_eq,walkB] exact mem_fold e _ (fun x h => by simp [h]) (by simp) (by simp) end P455RealizerGraph end /- Begin Problem455PaddedReadback (from finite-semigroup-identity-bases). -/ section namespace P455PaddedTiles open P455Witness variable {n w h : Nat} {M : MachineTable n} private theorem clip {v : Nat} (hv : 0 subst n · exact near_mono (role_near (marked_typed ok.1) role) (by decide) · have port := ok.2.1 exact near_trans (neighbor_paths cap f.dir port).1 (role_near (neighbor_target_record port) role) · have port := ok.2.2.1 exact 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 := by simpa [flagQ,hb] using h private 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.1 private 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.1 private 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.1 private 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.1 private 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) := by have sq := h.2.2.2.2.1 simpa [flagQ,b,d,V,Holds] using sq /-- Either the selected local neighbor is the second endpoint, or the certificate 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 := by have lc := ok.2.2.1 have succ := ok.2.2.2.1 unfold chosenSuccessor at succ dsimp only at succ split at succ next ret => rcases succ.2.1 with f|b · exact port_joined cap 4 (by decide) f · exact (port_joined cap 4 (by decide) b).symm next noReturn => have eq := succ.1 cases row : endOfRow ts e.a with | true => have bottom : ts.bottom e.a.tag = false := by simpa [row] using noReturn have target : e.down = e.b := by simpa [row,P455Witness.Holds] using eq exact 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 row have target : e.left = e.b := by simpa [row,odd,P455Witness.Holds] using eq exact target ▸ (right_paths cap (local_left lc left)).symm | false => have right : ts.right e.a.tag = false := by simpa [endOfRow,odd] using row have target : e.right = e.b := by simpa [row,odd,P455Witness.Holds] using eq exact 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) := by have lc := ok.2.2.1 cases 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 b exact ⟨near_mono (right_paths cap p).1 (by decide),neighbor_target_record (d := .right) p⟩ | left b => have p := local_left lc b exact ⟨near_mono (right_paths cap p).2 (by decide),neighbor_target_record (d := .left) p⟩ | down b => have p := local_down lc b exact ⟨near_mono (down_paths cap p).1 (by decide),neighbor_target_record (d := .down) p⟩ | up b => have p := local_up lc b exact ⟨near_mono (down_paths cap p).2 (by decide),neighbor_target_record (d := .up) p⟩ | diagonal rr dd => have p := local_right lc rr have q := (local_square lc rr dd).1 exact ⟨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 specified edge 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 := by obtain ⟨reach,recProof⟩ := active_owner cap ts e ok active have first := near_trans reach (role_near recProof role) exact ⟨near_mono first (by decide),near_trans (successor_joined cap ok).2 first⟩ end P455CertificateReach end /- Begin Problem455ContactLift (from finite-semigroup-identity-bases). -/ section namespace P455ContactLift open Problem455.Slots P455Witness P455Paths def Supplies (v : W) (h : Nat → W) (r x s : Nat) := v.count x = r ∧ s ∈ h x noncomputable def donor (v : W) (h : Nat → W) (r s : Nat) : Nat := by classical exact if hs : ∃ x, Supplies v h r x s then hs.choose else 0 theorem 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) := by intro s; have hs := cap s; simp only [List.count_append] at hs; omega theorem 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 := by classical have existsDonor : ∃ y, Supplies v h r y s := ⟨x,supply⟩ have other := existsDonor.choose_spec have 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.1 unfold 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 = r theorem guard_uniform {r allow mark v seed J} (uniform : ∀ x ∈ v, v.count x = r) : Guard r allow mark v seed J := by intro _ _ _ _ y hy obtain ⟨j,sub⟩ := hy have 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 t Supplies v h r y t ∧ x ≠ y ∧ Holds r allow mark v (contact r x y c) := by obtain ⟨i,slot,occ⟩ := P455ContactGeometry.contact_slot hc have ext := P455ContactGeometry.contact_excludes_image hr cap sup.1 sup.2 hc obtain ⟨y,_,ht,hy,ne⟩ := P455SlotOrigin.supplier v h l k x s t i r hr cap sup.1 sup.2 ext occ (guard i slot) 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 hc simpa 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) := by induction 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) := by induction p generalizing n s with | nil => exact ⟨True.intro,sup⟩ | cons bc rest ih => obtain ⟨b,c⟩ := bc have len : n+1+rest.length ≤ J := by simpa [Nat.add_assoc,Nat.add_comm 1 rest.length] using bound have g := guard _ (near_mono near (by omega)) obtain ⟨next,_,edge⟩ := contact_step hr cap sup g c walk.1 have more := near_trans near (near_one c edge) obtain ⟨tail,last⟩ := ih b (n+1) next more len walk.2 exact ⟨⟨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) := by have eq := donor_eq hr (factor_cap cap) start simpa only [eq] using transfer_from hr cap guard s p 0 (eq.symm ▸ start) (eq.symm ▸ near_self seed 0) (by simpa using bound) walk theorem 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 := by obtain ⟨p,w,ep,len⟩ := near obtain ⟨sw,sup⟩ := lift_walk hr cap start guard p (Nat.le_trans len bound) w rw [ep] at sup refine ⟨sup,relabel (donor v h r) p,sw,?_,by simpa [relabel] using len⟩ have eq := donor_eq hr (factor_cap cap) start rw [← eq,endpoint_relabel,ep] end P455ContactLift end /- Begin Problem455PortReflection (from finite-semigroup-identity-bases). -/ section namespace P455PortReflection open Problem455.Slots P455Witness P455ContactReflection P455ContactGeometry def 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 := by induction 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) := by simp only [earlyBefore,holds_all,List.mem_flatMap,List.mem_map] constructor · intro h a ha b hb exact h _ ⟨a,ha,b,hb,rfl⟩ · rintro h _ ⟨a,ha,b,hb,rfl⟩ exact h a ha b hb section Uniform variable {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 := by intro eq obtain ⟨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) recProof exact 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)) := by obtain ⟨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) recProof theorem 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) := by obtain ⟨ne,len,code,_,eq⟩ := recProof have 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 := by have 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 := by have distinct := record_roles_distinct hr cap n uni recProof intro z hz t ht eq simp [roles] at hz ht rcases hz with rfl | rfl <;> rcases ht with rfl | rfl <;> simp_all have 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 := by intro eq obtain ⟨hx,sa⟩ := ua s hs obtain ⟨_,tb⟩ := ub t ht rw [← eq] at tb have early : Holds r allow mark (l ++ v.flatMap h ++ k) (earlyDisjoint (roles a) (roles b)) := port.2.2.1 rcases 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 eq rcases 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 eq theorem 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 order theorem 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)) := by have 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 port have 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)) := by apply (earlyBefore_iff _ _).mpr intro u hu v' hv obtain ⟨i,hi,rfl⟩ := List.mem_map.mp hu obtain ⟨j,hj,rfl⟩ := List.mem_map.mp hv have pat := transfer [(i,2),(j,0)] (by intro e he simp only [List.mem_cons,List.not_mem_nil,or_false] at he rcases 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 pat refine ⟨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*phase have 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.1 simpa [eventMap, sendNode, i] using pat theorem 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)) := by have 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.1 exact ⟨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) := by have 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 port end Uniform /-- Structural independence of the ambient marking. Only a designated marked-bit query reads it. The record and ordering parts of a port can therefore be used with any source marking. -/ def markFree : Query → Bool | .markedBit .. => false | .both x y | .either x y => markFree x && markFree y | _ => true theorem 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 := by induction 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 free exact ⟨hx both.1 holds.1, hy both.2 holds.2⟩ | either x y hx hy => have both := Bool.and_eq_true_iff.mp free exact 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 := rfl theorem free_neighbor (ts : Tiles) (a b : Node) (dir : Dir) : markFree (neighbor ts a b dir) = true := by cases dir <;> rfl theorem 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) holds theorem 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) holds end P455PortReflection end /- Begin Problem455RealizerPrim (from finite-semigroup-identity-bases). -/ section /- Encoded first-order subroutines for the #455 computation. -/ namespace P455GraphPrim open P455EffectiveQ P455RealizerGraph variable {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) := by have 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) by simpa [PrimrecPred, Primrec₂] using hp) (Primrec.option_some.comp Primrec.snd) (.const none)).to₂ apply (Primrec.listFilterMap hl k).of_eq intro a induction l a with | nil => rfl | cons b bs ih => cases h : p a b <;> simp [h,ih] theorem join [DecidableEq B] : Primrec₂ (@joinAt B _) := by apply Primrec₂.mk apply Primrec.list_append.comp Primrec.snd apply Primrec.list_flatMap Primrec.snd apply Primrec₂.mk apply 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₂.mk apply 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) := by exact 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) := by let step (l : List B) (x : Nat × List (List B)) := [] :: l.flatMap (fun a => x.2.map (List.cons a)) have steprec : Primrec₂ step := by apply Primrec₂.mk apply Primrec.list_cons.comp (.const []) apply Primrec.list_flatMap Primrec.fst apply Primrec₂.mk apply 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_eq intro l n induction 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) := by apply Primrec.list_flatMap hd apply Primrec₂.mk apply Primrec.list_map · apply filter (hd.comp Primrec.fst) apply Primrec₂.mk apply 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.snd classical exact 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) := by apply ((Primrec.nat_lt.comp (Primrec.list_idxOf.comp hv hx) (Primrec.list_length.comp hx)).decide).of_eq intro 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) := by have piv := wordPool.comp hu have 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 => by rw [←walk_eq (e a) (u a) (v a)] apply Bool.eq_iff_iff.mpr simp 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) := by apply (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_eq intro a induction 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) := by apply anyB (wordPool.comp hv) apply Primrec₂.mk apply anyB (wordPool.comp (hv.comp Primrec.fst)) apply Primrec₂.mk exact (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)).decide theorem 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) := by apply anyB (wordPool.comp ht) apply Primrec₂.mk exact 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 P455GraphPrim end /- Begin Problem455MachineTable (from finite-semigroup-identity-bases). -/ section namespace P455MachineTable open P455MachineLocal P455PaddedTiles structure TM (g q : Nat) where marker : Fin g blank : Fin g blank_ne : blank≠marker start : Fin q accept : Fin q distinct : start≠accept delta : Fin q→Fin g→Ins (Fin g) (Fin q) keeps : ∀ z a,(delta z a).symbol=marker ↔ a=marker leftSafe : ∀ z,(delta z marker).dir≠.left stationary : 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+1 def enc (c : C g q) : Fin (g*(q+1)) := ⟨g*headIndex c.head+c.sym.val,by have v := c.sym.isLt have z : headIndex c.head ≤ q := by cases hh : c.head with | none => simp [headIndex] | some s => simp [headIndex]; have := s.isLt; omega have m := Nat.mul_le_mul_left g z rw [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/g let symbol := x.val%g let head := if e : 0 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 := by simpa [dec_enc] using congrArg (dec M) e def compile (M : TM g q) : MachineTable (g*(q+1)) where marker := 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 := by intro eq have 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 enc structure Config (g q : Nat) where tape : Nat→Fin g pos : Nat state : Fin q def 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 := by induction t with | zero => by_cases e : x=0 <;> simp [run,init,e,M.blank_ne] | succ t ih => change writeAt _ _ _ x=M.marker ↔ x=0 by_cases e : x=(run M t).pos · rw [writeAt,if_pos e,M.keeps,←e]; exact ih · simpa [writeAt,e] using ih theorem head_bound (M : TM g q) (t : Nat) : (run M t).pos ≤ t := by induction t with | zero => exact Nat.le_refl _ | succ t ih => change dest (_ : Ins (Fin g) (Fin q)).dir (run M t).pos≤t+1 cases d : (M.delta (run M t).state ((run M t).tape (run M t).pos)).dir <;> simp [dest] <;> omega theorem physical_safe {t w : Nat} (M : TM g q) (wide : t+1 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 := by by_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 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_x rw [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 := by have h := congrArg (List.count x) (exp.select_eq s [x] sub (by simpa using hx)) simpa [select] using h theorem 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 := by intro x by_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]; omega theorem 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 := by cases 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) := by obtain ⟨xc,yc⟩ := contact_counts (exp.small_cap hr cap) edge have used (a) (count : v.count a = r) : kept a := by apply Classical.byContradiction intro k have hm : a ∈ v := List.count_pos_iff.mp (by omega) have := (exp.gaps a hm k).1; omega have xx := used x xc have yy := used y yc have 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) := by refine ⟨old.1, P455ContactReflection.select_sees [x,y] _ pat ?_⟩ rw [eq x y xx yy] exact P455ContactReflection.sees_select _ _ _ inside old.2 cases c with | record tag rev => cases rev with | false => obtain ⟨ne,len,tag,bit,hp⟩ := edge exact ⟨ne,len,tag,bit,(eq x y xx yy).trans hp⟩ | true => obtain ⟨ne,len,tag,bit,hp⟩ := edge exact ⟨ne,len,tag,bit,(eq y x yy xx).trans hp⟩ | port port rev => obtain ⟨ne,_,_,early,order,_⟩ := edge refine ⟨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) order theorem 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 := by induction 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 := by obtain ⟨p,h,ep,le⟩ := near exact ⟨p,exp.walk hr cap s p h,ep,le⟩ /-- An occurrence in a small open slot contributes every letter of its expansion 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 := by obtain ⟨j,hj⟩ := ho have 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).2 obtain ⟨L,I,R,cut,idx,cons⟩ := P455SlotOrigin.slot_cut v x i bound have hy : y ∈ I := by apply (P455SlotOrigin.occupies_at_cut L I R x y cons).mp rw [←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 kx have 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 kx have ex := exp.literal x (by simp [cut]) kx have expanded : v.flatMap e = (L.flatMap e) ++ [x] ++ I.flatMap e ++ [x] ++ R.flatMap e := by simp [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 := by intro y ho obtain ⟨j,obs⟩ := ho have 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]; simp have claim := (original y (exp.in_original_slot x i y kx ⟨j,obs⟩ y mem)).2 exact (exp.count_eq v (fun _ h => h) y ky).symm.trans claim · have gap := exp.gaps y used ky obtain ⟨a,ha⟩ : ∃ a, a ∈ e y := by cases 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 the original 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 := by intro x near i hi obtain ⟨kx,slots⟩ := original x (exp.near hr cap near) exact exp.slot_guard x i kx (slots i hi) end P455Retained end /- Begin Problem455SourceFamilies (from finite-semigroup-identity-bases). -/ section /- Source interpretations of the designated slot and duplicate-neighbor certificates. Block distinctions require no repeated links to be read literally back in the source. The weaker name/count conclusions do not. -/ namespace P455SourceFamilies open P455Witness P455Paths P455ContactLift P455PortReflection Problem455.Slots def markNode (a : Node) : Marking := fun x y => x = a.owner ∧ y = a.mate def picked (s : SlotCertificate) := if s.startAtMate then s.anchor.mate else s.anchor.owner def 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 b theorem compressed_separates {r v} (cmp : Compressed r v) {a b : Nat} (ne : a ≠ b) : ¬ Problem455Swap.SameBlock r v a b := by intro same have joined := same.2.2 cases 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) := by apply remark _ obs cases c with | record tag rev => cases rev <;> rfl | port phase rev => rfl theorem 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 := by induction 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 := by cases 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.1 theorem 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)) := by cases a with | deficient s => exact lifted.elim | overflow xs => obtain ⟨f,len,nd,spec⟩ := lifted have 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 eq have bs : (x :: xs.map d).Pairwise (fun a b => ¬ Problem455Swap.SameBlock r u a b) := by rw [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 _).mpr intro q hq obtain ⟨z,hz,rfl⟩ := List.mem_map.mp hq obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hz have sp := spec a ha have out := inside (f a) sp.1 sp.2.2 exact 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⟩) lifted def SlotResult (r : Nat) (allow : Tag → Prop) (v : W) (h : Nat → W) (seed : Nat) (s : SlotCertificate) : Prop := let d := donor v h r let s' := sendSlot d s let m := markNode s'.anchor Holds 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 := by let d := donor v h r let m := markNode (sendNode d s.anchor) have seedEq : d (picked s) = seed := donor_eq hr (factor_cap cap) start have anch : V r allow mark (l ++ v.flatMap h ++ k) (markedNode s.anchor s.bit) := ok.1 have ports := record_pair (marked_typed anch) have rolesU : UniformOn r v h d (roles s.anchor) := by intro u mem have links : Near r allow mark (l ++ v.flatMap h ++ k) (picked s) u 1 := by rcases (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).1 have bit := reflect_markedNode hr cap s.anchor s.bit rolesU m (.inl ⟨rfl,rfl⟩) anch obtain ⟨len,outputWalk,terminal⟩ := slot_route s ok have walks := lift_walk hr cap start guard s.steps len outputWalk let endLabel := endpoint (picked s) s.steps have 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 _) ext have slot := valid_slot s.defect terminal have g := guard (d endLabel) towards s.terminalIndex slot have lf := P455TerminalTransfer.terminal v h l k (d endLabel) endLabel s.terminalIndex r hr cap en.1 en.2 g s.defect terminal have sw : Walk r allow m v seed (relabel d s.steps) := remark_walk _ _ walks.1 refine ⟨bit,sw,lf,?_⟩ intro cmp have 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) lf have pickEq : picked (sendSlot d s) = d (picked s) := by cases z : s.startAtMate <;> simp [picked,sendSlot,sendNode,z] refine ⟨bit,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩ apply (route_iff ..).mpr change 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.owner def FuncResult (r : Nat) (allow : Tag → Prop) (ts : Tiles) (v : W) (h : Nat → W) (f : FunctionalityCertificate) : Prop := let f' := sendFunc (donor v h r) f let m := markNode f'.anchor Holds 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 := by let d := donor v h r let 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) := by intro a ha have 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).1 have union (n : Node) (use : n=f.anchor ∨ n=f.b ∨ n=f.c) : UniformOn r v h d (roles f.anchor ++ roles n) := by intro a ha rcases List.mem_append.mp ha with h1|h2 · exact supplies _ (.inl rfl) _ h1 · exact supplies n use _ h2 have bit := reflect_markedNode hr cap f.anchor f.bit (supplies _ (.inl rfl)) m (.inl ⟨rfl,rfl⟩) ok.1 have 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 := by cases 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) := by intro eq have same := Problem455SameDonor.sameDonor v h _ sb.1 (factor_cap cap) _ _ sb.2 (eq.symm ▸ sc.2) apply ok.2.2.2.1 exact Problem455Swap.sameBlock_factor ⟨l,k,rfl⟩ (fun a => by rw [Problem455BlockBridge.occ_count]; exact cap a) same have mapped (n : Node) : roleOf f.distinguishMate (sendNode d n) = d (roleOf f.distinguishMate n) := by cases f.distinguishMate <;> rfl have neq : roleOf f.distinguishMate (sendNode d f.b) ≠ roleOf f.distinguishMate (sendNode d f.c) := by simpa only [mapped] using neat exact ⟨bit,b,c,neq,fun cmp => ⟨bit,b,c,compressed_separates cmp neq,True.intro⟩⟩ end P455SourceFamilies end /- Begin Problem455EdgeSource (from finite-semigroup-identity-bases). -/ section namespace P455EdgeSource open P455Witness P455Paths P455CertificateReach P455PortReflection P455ContactReflection open P455ContactLift def 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) := by cases b · exact True.intro · exact f rfl private 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 supplies the 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) := by have lc := ok.2.2.1 have succ := ok.2.2.2.1 unfold chosenSuccessor at succ dsimp only at succ split at succ next ret => exact ⟨4,succ.2.1⟩ next noReturn => have eq := succ.1 cases row : endOfRow ts e.a with | true => have down : ts.bottom e.a.tag = false := by simpa [row] using noReturn have target : e.down = e.b := by simpa [row,P455Witness.Holds] using eq have ok := read_guard (by simp [down]) lc.2.2.1 exact ⟨_,.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 row have target : e.left = e.b := by simpa [row,odd,P455Witness.Holds] using eq have ok := read_guard (by simp [left]) lc.2.1 exact ⟨_,.inr (target ▸ ok.2.1)⟩ | false => have right : ts.right e.a.tag = false := by simpa [endOfRow,odd] using row have target : e.right = e.b := by simpa [row,odd,P455Witness.Holds] using eq have ok := read_guard (by simp [right]) lc.1 exact ⟨_,.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) := by have both {n m} (an : Active ts e n) (am : Active ts e m) : UniformOn r v h d (roles n ++ roles m) := by intro y hy rcases List.mem_append.mp hy with h|h · exact supply n an y h · exact supply m am y h have localRight (rr : ts.right e.a.tag = false) := read_guard (by simp [rr]) ok.2.2.1.1 have localLeft (ll : ts.left e.a.tag = false) := read_guard (by simp [ll]) ok.2.2.1.2.1 have localDown (dd : ts.bottom e.a.tag = false) := read_guard (by simp [dd]) ok.2.2.1.2.2.1 have localUp (uu : ts.top e.a.tag = false) := read_guard (by simp [uu]) ok.2.2.1.2.2.2.1 have 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.1 have hs : Holds r allow (endpointMarks d e) v (localCert ts (sendEdge d e)) := by refine ⟨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 b exact reflect_rightward hr cap ts _ _ (both .anchor (.right rr)) (localRight rr) · have ll : ts.left e.a.tag = false := by simpa [sendEdge,sendNode] using b exact reflect_rightward hr cap ts _ _ (both (.left ll) .anchor) (localLeft ll) · have dd : ts.bottom e.a.tag = false := by simpa [sendEdge,sendNode] using b exact reflect_downward hr cap ts _ _ (both .anchor (.down dd)) (localDown dd) · have uu : ts.top e.a.tag = false := by simpa [sendEdge,sendNode] using b exact 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 := by simpa [sendEdge,sendNode] using b exact ⟨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.1 have bBit := reflect_markedNode hr cap e.b false (supply _ .successor) (endpointMarks d e) (Or.inl (Or.inr ⟨rfl,rfl⟩)) ok.2.1 refine ⟨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))) := by obtain ⟨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) ord have suc := ok.2.2.2.1 unfold 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 suc next ret => rw [if_pos ret] have ord := rel [(e.b.owner,0),(e.a.owner,0)] (by simp [roles]) suc.2.2.1 refine ⟨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.2 refine ⟨?_,ord⟩ change (if endOfRow ts e.a then sendNode d e.down else if ts.oddRow e.a.tag then sendNode d e.left else sendNode d e.right) = sendNode d e.b have eq := suc.1 cases 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 supplies every 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) := by apply edge_source hr cap ts e _ ok intro n active y hy have role : y = n.owner ∨ y = n.mate := by simpa [roles] using hy obtain ⟨a,b⟩ := edge_reach cap ts e ok active role have 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 <;> assumption exact (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.a Supplies 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) := by cases 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 _ ok intro n active y hy have role : y = n.owner ∨ y = n.mate := by simpa [roles] using hy obtain ⟨a,b⟩ := edge_reach cap ts e ok active role cases atSecond · have step := (record_pair (marked_typed ok.1)).2 exact (lift_near hr cap start guard budget (near_trans step a)).1 · have step := (record_pair (marked_typed ok.2.1)).2 exact (lift_near hr cap start guard budget (near_trans step b)).1 end P455EdgeSource end /- Begin Problem455RealizerClass (from finite-semigroup-identity-bases). -/ section namespace P455ClassPrim open P455EffectiveQ P455GraphPrim variable {A : Type} [Primcodable A] abbrev Raw := Option W theorem 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) := by let h (a : A) (w : W) := goodB (e a) (T a) w have 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) := by let inside (a : A) (u v : W) := goodB (e a) (T a) u && goodB (e a) (T a) v && walkB (e a) u v have 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 P455ClassPrim end /- Begin Problem455RealizerFrameOps (from finite-semigroup-identity-bases). -/ section namespace P455FramePrim open P455Closure P455EffectiveQ P455GraphPrim abbrev Tag := List Bool abbrev Marks := List (Nat×Nat) abbrev PairList := List (List Nat×Bool) abbrev FrameData := Nat × W × W × Nat × Tag × PairList × W × W × W def packing : Frame Nat ≃ FrameData where toFun 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 _ := rfl right_inv _ := rfl instance framePrimcodable : Primcodable (Frame Nat) := Primcodable.ofEquiv _ packing theorem pack : Primrec packing := Primrec.of_equiv theorem unpack : Primrec packing.symm := Primrec.of_equiv_symm variable {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) := by apply (Primrec.not.comp (anyB hl (Primrec.not.comp₂ hp))).of_eq intro 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) := by apply (Primrec.list_length.comp (P455GraphPrim.filter hl ((Primrec.beq.comp Primrec.snd (hz.comp Primrec.fst)).to₂))).of_eq intro a simp [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 := by apply (allB hl ((Primrec.eq.comp (countN Primrec.snd (hl.comp Primrec.fst)) (.const 1)).decide.to₂)).of_eq intro a apply Bool.eq_iff_iff.mpr simp 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 pTail theorem 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) q theorem 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 P455FramePrim end /- Begin Problem455MachineTrace (from finite-semigroup-identity-bases). -/ section namespace P455MachineTable open P455MachineLocal P455PaddedTiles private theorem left_agree {u v : Nat→Fin n} {w x : Nat} (hx : x simp [leftAt,e,eq (x-1) (by omega)] private theorem right_agree {u v : Nat→Fin n} {w x : Nat} (hx : x simp [exits,dest] at * <;> omega theorem agrees (M : TM g q) {w s : Nat} (T : AcceptingTrace (compile M) w s) : ∀ t,t≤s → (run M t).pos intro _ refine ⟨T.positive,?_⟩ intro x hx rw [T.start x hx] by_cases e : x=0 <;> simp [compile,row,run,init,atCell,e] | succ t ih => intro st obtain ⟨hp,eq⟩ := ih (by omega) have moves (x : Nat) (hx : x change pos=0 at at0; change st=M.accept at state subst pos; subst st change tape 0=M.marker at eq0 have 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-row stutter, 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 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) := by constructor · 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 trace_stutters M T)) end P455MachineTable end /- Begin Problem455OriginalWalk (from finite-semigroup-identity-bases). -/ section /- End-to-end transport of a designated marked-word path to its original word after expanding the small rule's gaps. Both valuations may use the same Nat name for unrelated alphabet entries. Only e expands the rule; h supplies the actual tester representatives. -/ namespace P455OriginalWalk open Problem455.Slots P455Witness P455Paths P455ContactLift P455Retained def 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 its reached labels are replaced by their unique donors. No injectivity of the entire 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 r let 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) := by let d := donor v h r have pos : 0 < r := by omega have eq : d s = seed := donor_eq pos (factor_cap capZ) start obtain ⟨small,supply⟩ := P455ContactLift.lift_walk pos capZ start (exp.guard hr capU original) p len walk have large := exp.walk hr capU seed _ small have 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).1 exact ⟨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 a Near 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 := by obtain ⟨p,walk,ea,len⟩ := near obtain ⟨w,ep,lp,kp,small,full⟩ := lift_walk exp hr capU original capZ start p (Nat.le_trans len bound) walk rw [ea] at ep kp small full exact ⟨⟨_,w,ep,lp ▸ len⟩,kp,small,full⟩ end P455OriginalWalk end /- Begin Problem455OriginalEdges (from finite-semigroup-identity-bases). -/ section namespace P455OriginalEdges open Problem455.Slots P455Witness P455Paths P455Retained P455PortReflection section variable {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 := by obtain ⟨cnt,cn'⟩ := record_counts (exp.small_cap hr cap) recProof intro x hx have ct : v.count x = r := by rcases (show x = a.owner ∨ x = a.mate by simpa [roles] using hx) with eq|eq · exact eq ▸ cnt · exact eq ▸ cn' apply Classical.byContradiction intro gap have := (exp.gaps x (List.count_pos_iff.mp (by omega)) gap).1 omega theorem 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) := by have 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) recProof theorem 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) := by let ks := p.map Prod.fst have all : ∀ a ∈ ks, kept a := by intro a h obtain ⟨ev,he,rfl⟩ := List.mem_map.mp h exact labels ev he refine ⟨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.2 theorem 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]) ord theorem 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) := by obtain ⟨ra,rb,early,order,_⟩ := port have ka := kept_roles exp hr cap ra have kb := kept_roles exp hr cap rb have 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) := by apply (earlyBefore_iff _ _).mpr exact 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 ka have kb' : kept b.owner ∧ kept b.mate := by simpa [roles] using kb exact expand_order exp (by simp [ka'.1,ka'.2,kb'.1,kb'.2]) order theorem 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) := by have p := q.2.1 exact ⟨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) := by cases 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 q private 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) := by cases b · exact True.intro · exact f h theorem 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) := by obtain ⟨a,b,localQ,succ,_⟩ := query refine ⟨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 succ next 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⟩ end end P455OriginalEdges end /- Begin Problem455Compression (from finite-semigroup-identity-bases). -/ section namespace P455Compression open P455Witness P455Retained inductive Piece where | literal (a : Nat) | gap (w : W) deriving DecidableEq def body : Piece → W | .literal a => [a] | .gap w => w def prependOutside (a : Nat) : List Piece → List Piece | .gap w :: tail => .gap (a::w) :: tail | cs => .gap [a] :: cs def pieces (names : W) : W → List Piece | [] => [] | a :: u => let rest := pieces names u if a ∈ names then .literal a :: rest else prependOutside a rest def 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 this expresses maximality of every omitted run, also at the two ends. -/ def noTouch : List Piece → Prop | .gap _ :: .gap _ :: _ => False | _ :: tail => noTouch tail | [] => True private theorem prepend_body (a : Nat) (cs : List Piece) : (prependOutside a cs).flatMap body = a :: cs.flatMap body := by cases cs with | nil => rfl | cons p tail => cases p <;> rfl theorem decoded (names u : W) : (pieces names u).flatMap body = u := by induction 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 := by cases 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 h simp 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 := by induction 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 ih private theorem prepend_sep {cs : List Piece} (a : Nat) (ok : noTouch cs) : noTouch (prependOutside a cs) := by cases 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 ok theorem maximal (names u : W) : noTouch (pieces names u) := by induction 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 + 1 private theorem le_sum {a : Nat} {w : W} (ha : a ∈ w) : a ≤ w.sum := by induction 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; omega def code : Nat → List Piece → W | _,[] => [] | n,.literal a :: cs => a :: code (n+1) cs | n,.gap _ :: cs => n :: code (n+1) cs def 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 a def 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] := by induction 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 := by induction 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 mem private 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 := by induction 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 := by intro h have := large n (low_kept cs names goodTail n (n+1) (by omega) h) omega have eq : (code (n+1) cs).flatMap (lookup n (.gap w :: cs)) = (code (n+1) cs).flatMap (lookup (n+1) cs) := by simp only [List.flatMap_def] apply congrArg List.flatten exact List.map_congr_left (fun a ha => by have 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 body rw [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 := by induction cs generalizing n with | nil => simp [code] | cons c cs ih => intro g use outside 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) g cases 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 use simpa [code,lookup,List.count_cons,dif,Ne.symm dif] using tail occurs outside | gap w => by_cases same : g=n · subst g have 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 use simpa [code,lookup,List.count_cons,same,Ne.symm same] using tail occurs outside theorem 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) where literal 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 := by intro orig apply unkept apply low_kept (pieces names u) names (pieces_good names u) g (base u names) _ use have := le_sum orig unfold base; omega theorem counts_retained (u names : W) (x : Nat) (hx : x ∈ names) : (small u names).count x = u.count x := by have c := (canonical u names).count_eq (small u names) (fun _ h => h) x hx rw [recover] at c exact c.symm end P455Compression end /- Begin Problem455DefectProjection (from finite-semigroup-identity-bases). -/ section namespace P455DefectProjection open P455Witness P455Paths P455SourceFamilies Problem455.Slots theorem select_sub (keep smaller u : W) (hs : ∀ a ∈ smaller, a ∈ keep) : select smaller (select keep u) = select smaller u := by induction 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) := by intro a by_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) := by obtain ⟨ne,len,tag,mk,eq⟩ := obs refine ⟨ne,len,tag,mk,(select_sub keep [n.owner,n.mate] u ?_).trans eq⟩ simpa using And.intro ho hm theorem 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) := by obtain ⟨ne,len,ok,bit,eq⟩ := obs exact ⟨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) := by cases 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⟩ := obs refine ⟨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 := by induction p generalizing a with | nil => trivial | cons bc rest ih => obtain ⟨b,c⟩ := bc have 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 := by induction 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 := by obtain ⟨j,h⟩ := obs exact ⟨j,P455ContactReflection.sees_select keep u _ (by simp [hb,ht]) h⟩ /-- A genuine slot component of alphabet size at most nine suffices for a deficient occupant. The cap and all unchanged occurrence indices are derived in the projection. Both orientations and length-zero routes are 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) := by let a := if side then n.mate else n.owner obtain ⟨p,w,ep,len⟩ := near let keep := n.owner :: n.mate :: bad :: p.map Prod.fst have 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 ins let 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 ..).mpr refine ⟨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 < r rw [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) := by obtain ⟨keep,s,len,ho,hm,_,_,anc,bs,cp,h⟩ := bounded_defect_kind cap n bit side t i bad anchor near slot occ deficient exact ⟨keep,s,len,ho,hm,anc,bs,cp,h⟩ end P455DefectProjection end /- Begin Problem455FirstRewrite (from finite-semigroup-identity-bases). -/ section namespace P455FirstRewrite abbrev W := List Nat abbrev Sub := Nat → W def 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 ++ q abbrev Derives (G : W → W → Prop) := P455Quotient.Walk (Step G) /-- A deduction entirely in a two-word class contains an actual one-step instance 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 := by suffices go : ∀ w, Derives G A w → w = A ∨ Step G A B by exact (go B path).resolve_left ne.symm intro w walk induction 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 done def 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 q private theorem filter_erase (f : Nat → Bool) (a : Nat) (w : W) : (w.erase a).filter f = (w.filter f).erase a := by induction w with | nil => rfl | cons x xs ih => by_cases e : x = a · subst x by_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 := by induction 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 := by induction 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)) mz exact ⟨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 := by induction 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 noncommuting images 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 := by induction 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 m have cross (z) (mz : z ∈ L) : g a ++ g z = g z ++ g a := by apply Classical.byContradiction intro bad have pair := pairs a z bad obtain ⟨t,eq⟩ := prefix_head n mz rw [proj_append,eq] at pair have az : a = z := by simpa [proj] using congrArg List.head? pair exact n (az ▸ mz) have er : (L ++ a :: R).erase a = L ++ R := by rw [List.erase_append_right _ n, List.erase_cons_head] have cnt (x) : u.count x = (L ++ R).count x := by have orig := counts x simp only [List.count_append,List.count_cons] at orig ⊢ omega have rest (i j) (bad : g i ++ g j ≠ g j ++ g i) : proj i j u = proj i j (L ++ R) := by have eq := congrArg (fun w : W => w.erase a) (pairs i j bad) unfold proj at eq rw [← filter_erase, ← filter_erase, List.erase_cons_head, er] at eq exact eq have sub := ih cnt rest simp 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 where unary : ∀ 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 = r private 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 := by intro x obtain ⟨a,hm⟩ : ∃ a, a ∈ h x := by cases 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 hm have mul := Nat.mul_le_mul_left (u.count x) pos have ct := P455DonorInterval.split_contributions h u x a have bound := cap a simp only [List.count_append] at bound simp only [Nat.mul_one] at mul omega private 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) := by induction 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]; omega private 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] := by cases 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) := by rw [e]; simp [Problem455Swap.bigram,Problem455Swap.hit] <;> omega have lo := counted_edge h x a b edge u let U := p ++ u.flatMap h ++ q have lower : r ≤ Problem455Swap.bigram a b U := by dsimp [U]; rw [Problem455Swap.bigram_append,Problem455Swap.bigram_append]; omega have upper := Problem455Swap.out_bound a b (b+1) (by omega) U rw [Problem455BlockBridge.occ_count] at upper have hc : U.count a ≤ r := cap a exact 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)) := by induction 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] := by by_cases cb : c = b <;> by_cases db : d = b <;> simp_all [proj] /-- Every literal name in a changed binary projection is the singleton image of 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] := by have cu := cap_rule ne cap have counts (x) : u.count x = v.count x := by have eq := rule.unary x have bound := cu x omega have cv : P455Quotient.Cap r v := fun x => counts x ▸ cu x let g : Sub := fun x => proj a b (h x) apply Classical.byContradiction intro absent apply changed simp 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 := by apply Classical.byContradiction intro diff obtain ⟨ci,cj⟩ := rule.binary cu cv i j diff obtain ⟨c,ec⟩ := singleton ne cap compressed ci obtain ⟨d,ed⟩ := singleton ne cap compressed cj have 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 bad simpa [g,ec,ed] using projected_commutes_without a b c d ca da rw [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 a numeric 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 := by induction D generalizing C with | nil => simp | cons a t ih => obtain ⟨fresh,tail⟩ := List.nodup_cons.mp uniq have mem := sub a List.mem_cons_self have 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 mem have pos : 0 < C.length := by cases C <;> simp_all simp only [List.length_cons] omega /-- Any explicit list of rule variables covering the matched side must have at 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 := by have sub (a) (ma : a ∈ D) : a ∈ C.map (fun x => (h x).headD 0) := by obtain ⟨b,diff⟩ := changes a ma obtain ⟨x,mx,e⟩ := changed_name hr ne cap compressed rule a b diff exact 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 := by induction 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 := by induction 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)).length theorem rank_swap (u v : W) : rank u v = rank v u := by apply 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 operation alone occurs in rule terms. Empty contexts use the unit when evaluated. -/ structure Model (A : Type) where op : A → A → A unit : A assoc : ∀ x y z, op (op x y) z = op x (op y z) oneL : ∀ x, op unit x = x oneR : ∀ x, op x unit = x namespace Model variable {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 v theorem eval_append (f : Nat → A) (u v : W) : M.eval f (u ++ v) = M.op (M.eval f u) (M.eval f v) := by induction 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 := by induction 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 := by obtain ⟨u,v,p,q,h,orient,_,_,_,rfl,rfl⟩ := s intro f simp 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 := by induction 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 the distinguished identity and exhaustion of its semantic class are separate. -/ structure RankWitness {A : Type} (M : Model A) (r : Nat) (U V D : W) : Prop where nonempty : U ≠ [] ∧ V ≠ [] different : U ≠ V identity : M.Valid U V two : ∀ w, M.Valid U w → w = U ∨ w = V cap : P455Quotient.Cap r U compressed : P455SourceFamilies.Compressed r U distinct : D.Nodup participants : ∀ 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 := by have iden := M.step_sound valid s have direct := (wit.two T iden).resolve_left diff.symm subst T obtain ⟨u,v,p,q,h,oriented,_,_,ne,eq1,eq2⟩ := s have 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 := by apply instance_rank hr ne (eq1 ▸ wit.cap) (eq1 ▸ wit.compressed) (testers _ _ vr) wit.distinct cover simpa only [← eq1, ← eq2] using wit.participants rcases 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 assumption about 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 := by let sizes := G.map (fun t => rank t.1 t.2) obtain ⟨U,V,D,w,large⟩ := witnesses sizes.sum refine ⟨U,V,w.nonempty.1,w.nonempty.2,w.identity,?_⟩ intro derivation obtain ⟨u,v,mem,bound⟩ := derivation_rank hr w testers valid derivation have 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 := by induction 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; omega have := less sizes (rank u v) inSizes omega end P455FirstRewrite end /- Begin Problem455LiteralMovePrim (from finite-semigroup-identity-bases). -/ section /- Primitive recursive literal-move search on standard natural-number encodings, uniformly in the cap, tags and finitely stored mark relation. -/ namespace P455FrameProof set_option maxHeartbeats 450000 open P455Closure P455EffectiveQ P455GraphPrim P455FramePrim open 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 := by rw [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 := by apply Primrec.primrecPred apply (allB hl hp).of_eq intro a apply Bool.eq_iff_iff.mpr simp 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) := by apply allB hw exact (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) := by unfold validB apply PrimrecPred.decide let Fp := P455FramePrim.p.comp hf let Fq := P455FramePrim.q.comp hf let Ft := P455FramePrim.tag.comp hf let Fm := P455FramePrim.middle.comp hf have apart : PrimrecPred (fun a => ∀ x∈(f a).p, x∉(f a).q) := by apply forNames Fp exact (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) := by apply forNames Fp apply Primrec₂.mk apply PrimrecPred.decide apply forNames (Fq.comp Primrec.fst) apply Primrec₂.mk have old : Primrec (fun s : (A×Nat)×Nat => marks s.1.1) := (hm.comp Primrec.fst).comp Primrec.fst have 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))).decide have saturated : PrimrecPred (fun a => ∀ x∈(f a).p++(f a).q, ((f a).core false).count x = r a) := by apply 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.primrecPred apply PrimrecPred.and (Primrec.eq.comp (Primrec.list_map Fm (Primrec.snd.comp₂ Primrec₂.right)) (phases.comp Ft)) apply PrimrecPred.and (nodup Fp).primrecPred apply PrimrecPred.and (nodup Fq).primrecPred apply PrimrecPred.and apart apply PrimrecPred.and marksOK exact saturated theorem entriesRec {w : A → W} (hw : Primrec w) : Primrec fun a => entries (w a) := by apply Primrec.list_flatMap (wordPool.comp hw) apply Primrec₂.mk exact 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) := by simp 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) := by apply Primrec.list_flatMap hx apply Primrec₂.mk apply 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 × W private 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 := by apply Primrec₂.mk have tail1 : Primrec (fun s : Tag × Body => s.2.2) := Primrec.snd.comp Primrec.snd have tail2 := Primrec.snd.comp tail1 have tail3 := Primrec.snd.comp tail2 have tail4 := Primrec.snd.comp tail3 exact 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) := by apply Primrec.list_flatMap ht apply Primrec₂.mk let U : (A × Tag) → W := fun s => w s.1 let 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).length have hU : Primrec U := hw.comp Primrec.fst have hS : Primrec S := wordPool.comp hU have 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_eq intro s simp only [map_choices, insertTag, packing] rfl theorem 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) := by apply 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₂.mk apply 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₂.mk apply anyB (wordPool.comp ((hu.comp Primrec.fst).comp Primrec.fst)) apply Primrec₂.mk apply anyB (wordPool.comp (((hu.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst)) apply Primrec₂.mk let 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.snd apply PrimrecPred.decide exact 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 P455FrameProof end /- Begin Problem455MachineCleanup (from finite-semigroup-identity-bases). -/ section namespace P455MachineCleanup open P455MachineLocal P455MachineTable P455PaddedTiles structure Ordinary (g q : Nat) where marker : Fin g blank : Fin g blank_ne : blank≠marker start : Fin q delta : 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≠.left def 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 ⟨cleanState q,a,.stay⟩ | some i => extend i else if z.val=q then if 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⟩ := by simp [trans,cleanState] def normalized (M : Ordinary g q) : TM g (q+2) where marker := M.marker blank := M.blank blank_ne := M.blank_ne start := old M.start accept := acceptState q distinct := by intro e; have v := congrArg Fin.val e; change M.start.val=q+1 at v; have := M.start.isLt; omega delta := trans M keeps := by intro z a unfold trans split next bound => cases e : M.delta ⟨z.val,bound⟩ a with | none => rfl | some i => exact M.keeps _ _ _ e next => split · split <;> rfl · rfl leftSafe := by intro z unfold trans split next bound => cases e : M.delta ⟨z.val,bound⟩ M.marker with | none => simp | some i => exact M.leftSafe _ _ e next => split <;> simp stationary := by simp [trans,acceptState,show ¬q+1if 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)=none def 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 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 := by rw [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 := by induction p with | zero => intro t pos state have marker := (marker_iff (normalized M) t 0).mpr rfl change (run (normalized M) t).tape 0=M.marker at marker refine ⟨t+1,?_⟩ change dest (trans M _ _).dir _=0 ∧ (trans M _ _).state=acceptState q rw [state,pos,marker,clean_step] simp [dest] | succ p ih => intro t pos state have neq : (run (normalized M) t).tape (p+1)≠M.marker := by intro e; have z := (marker_iff (normalized M) t (p+1)).mp e; omega apply ih (t+1) · change dest (trans M _ _).dir _=p rw [state,pos,clean_step,if_neg neq]; simp [dest] · change (trans M _ _).state=cleanState q rw [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 by_cases early : ∃ i,iearly ⟨i,lt,st⟩⟩ theorem halts_iff_genuine (M : Ordinary g q) : (∃ t,stopped M t) ↔ ∃ s,Genuine (normalized M) s := by constructor · rintro ⟨t,yes⟩ obtain ⟨j,st,prior⟩ := first_stop M t yes have exactAt := simulates M j prior have 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⟩ := by rw [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.byContradiction intro none have eq := simulates M s (fun j _ h=>none ⟨j,h⟩) rw [eq] at accept have indices := congrArg Fin.val accept change (original M s).state.val=q+1 at indices have := (original M s).state.isLt; omega /-- Compilation targets the very same numerical tile system as the word testers. 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 exact small | overflow xs => obtain ⟨assign,len,nd,valid⟩ := small refine ⟨assign,len,nd,?_⟩ intro a ha obtain ⟨obs,ha',cnt⟩ := valid a ha have used : assign a ∈ v := List.count_pos_iff.mp (by omega) have keep : kept (assign a) := by apply Classical.byContradiction intro gap have := (exp.gaps (assign a) used gap).1 omega have hx : assign a ∈ e (assign a) := by rw [exp.literal _ used keep]; simp exact ⟨exp.in_original_slot x i _ kx obs _ hx,ha',(exp.count_eq _ (fun _ h => h) _ keep).trans cnt⟩ end P455OriginalTerminal end /- Begin Problem455CompressedFrame (from finite-semigroup-identity-bases). -/ section namespace P455CompressedFrame open P455Closure P455Compression P455Uncrossed private theorem prepend_cut (a x : Nat) (cs tail : List Piece) : prependOutside a (cs ++ .literal x :: tail) = prependOutside a cs ++ .literal x :: tail := by cases cs with | nil => rfl | cons p cs => cases p <;> rfl private 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 := by induction 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 := by induction 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).length private 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 := by simp 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 x private 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) es private def finish (names : W) (n : Nat) : List (W × Bool) → Nat | [] => n | (u,_)::es => finish names (n+span names u+1) es private 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 := by induction es generalizing n with | nil => simp [middleWord,encodeMiddle,finish] | cons e es ih => obtain ⟨gap,b⟩ := e have 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 := by induction 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 := by unfold Frame.mid middleWord congr 1 funext e cases 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.beforeMutable private 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 := by cases 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 := by induction 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 := by cases 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.middle let 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+6 let n := finish names head f.middle let p := n+span names f.beforeMutable+2 let q := p+span names f.beforeFinalP+1 let 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 := by dsimp only intro b let head := start+span names l+6 let g := make f names x y head have gp : g.p = [x] := rfl have gq : g.q = [y] := rfl change _ = side g _ _ b cases 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 rfl private 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) := by induction 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 gap variables 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 := by unfold expand rw [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_congr intro n rfl /-- For any common retained list containing x and y, both canonical shorter words 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) := by let start := base (side f l k false) names let head := start+span names l+6 let n := finish names head f.middle let p := n+span names f.beforeMutable+2 let q := p+span names f.beforeFinalP+1 let g := make f names x y head let left := enc names start l let right := enc names (q+span names f.beforeFinalQ+1) k have gp : g.p = [x] := rfl have gq : g.q = [y] := rfl have eq (b : Bool) : small (side f l k b) names = side g left right b := by unfold small rw [same_base f l k names hp hq b] exact enc_frame f l k names hx hy hp hq start b have bound : Cap r (side g left right origBit) := by rw [← eq] apply (canonical (side f l k origBit) names).small_cap (by have := valid.1; omega) rw [recover] exact cap have v : g.Valid r allow (fun _ _ => False) := by apply 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 · simp refine ⟨g,left,right,gp,gq,v,eq,?_⟩ intro b rw [← 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 P455CompressedFrame end /- Begin Problem455DefectRename (from finite-semigroup-identity-bases). -/ section namespace P455DefectRename open P455Witness P455Paths P455ContactLift P455SourceFamilies open P455ContactReflection P455PortReflection P455DefectProjection Problem455.Slots def decode (keep : W) (i : Nat) : Nat := (keep[i]?).getD 0 theorem decode_idx (keep : W) {a : Nat} (h : a ∈ keep) : decode keep (keep.idxOf a) = a := by induction 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 ha theorem decode_map {keep w : W} (hs : ∀ a ∈ w, a ∈ keep) : (w.map keep.idxOf).map (decode keep) = w := by rw [List.map_map] calc _ = w.map id := List.map_congr_left (fun a ha => decode_idx keep (hs a ha)) _ = w := List.map_id w def extend (keep : W) (a : Nat) := if a ∈ keep then keep.idxOf a else keep.length + a theorem extend_inj (keep : W) {a b : Nat} (h : extend keep a = extend keep b) : a = b := by by_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 · omega abbrev Injects (d : Nat → Nat) := ∀ {a b}, d a = d b → a = b theorem select_map_inj (d : Nat → Nat) (inj : Injects d) (keep w : W) : select (keep.map d) (w.map d) = (select keep w).map d := by induction w with | nil => rfl | cons a w ih => have iff : d a ∈ keep.map d ↔ a ∈ keep := by constructor · intro h; obtain ⟨b,hb,eq⟩ := List.mem_map.mp h; exact inj eq ▸ hb · exact List.mem_map_of_mem by_cases ha : a ∈ keep <;> simp_all [select] theorem kept {keep w : W} {a : Nat} (h : a ∈ select keep w) : a ∈ keep := by simpa using (List.mem_filter.mp h).2 theorem 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) := by have 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) (by intro a ha; have hxy : a = x ∨ a = y := by simpa using kept ha rcases hxy with rfl|rfl <;> assumption)] at h simpa [extend,hx,hy] using h.symm theorem count_rename (d : Nat → Nat) (inj : Injects d) (w : W) (a : Nat) : (w.map d).count (d a) = w.count a := by induction 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) := by intro a by_cases mem : a ∈ w.map d · obtain ⟨b,_,rfl⟩ := List.mem_map.mp mem simpa 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)) := by unfold 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))) := by refine ⟨?_,rename_sees d inj h.2⟩ intro e he; obtain ⟨f,hf,rfl⟩ := List.mem_map.mp he; exact h.1 f hf theorem 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 := by rw [← map_profile d a b tag bit, ← h, ← select_map_inj d inj [a,b] w] rfl theorem 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) := by obtain ⟨ne,len,ok,bit,pr⟩ := h exact ⟨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) := by cases c with | record tag rev => cases rev <;> exact rename_record d inj h | port phase rev => obtain ⟨ab,ac,bc,early,obs,last⟩ := h refine ⟨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 _ obs theorem 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) := by induction 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) := by obtain ⟨len,walk,term⟩ := slot_route s h let start := picked s have start' : picked (sendSlot d s) = d start := by cases side : s.startAtMate <;> simp [sendSlot,picked,sendNode,start,side] rw [kind] at term obtain ⟨⟨slot,j,seen⟩,cnt⟩ := term refine ⟨rename_marked d inj s.anchor s.bit h.1,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩ apply (route_iff ..).mpr change 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) := by obtain ⟨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 deficient let d := extend keep have 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 ha exact 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 valid end P455DefectRename end /- Begin Problem455BlockSeparators (from finite-semigroup-identity-bases). -/ section namespace P455BlockSeparators open 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 c theorem prepend {e a b c} (h : e a b) (p : Directed e b c) : Directed e a c := by induction p with | refl => exact .snoc (.refl _) h | snoc _ last ih => exact .snoc ih last theorem split_first {e a b} (p : Directed e a b) : a = b ∨ ∃ c, e a c ∧ Directed e c b := by induction 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 := by induction 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 := by apply orient _ _ same.2.2 · intro x y z xy xz apply Classical.byContradiction; intro ne have h := out_bound x y z ne w rw [show bigram x y w = r from xy,show bigram x z w = r from xz,Problem455BlockBridge.occ_count] at h have hx := cap x; omega · intro x y z yx zx apply Classical.byContradiction; intro ne have 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 h have 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 w theorem rows_length (a : Nat) (w : W) : (rows a w).length = w.count a := by induction 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 repeated link. This includes equality of the entire remaining suffix, rather than 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 w private theorem edgeRows_length (a b : Nat) (w : W) : (edgeRows a b w).length = bigram a b w := by induction 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) := by induction w with | nil => exact .slnil | cons c w ih => by_cases k : c = a · subst c by_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 ih private theorem edge_sub_right (a b : Nat) (w : W) : (edgeRows a b w).Sublist (rows b w.tail) := by induction 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 x by_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 ih theorem 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) := by have l := edge_sub_left a b w have f := edge_sub_right a b w have s : (rows b w.tail).Sublist (rows b w) := by cases w with | nil => exact .slnil | cons x t => by_cases eq : b=x · simp [rows,eq] · simp [rows,eq] have t := f.trans s have len : (edgeRows a b w).length = r := (edgeRows_length ..).trans link have 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 ++ ·) := by induction p with | refl => exact ⟨[],by simp⟩ | @snoc y z prev edge ih => obtain ⟨pre,h⟩ := ih refine ⟨pre ++ [y],?_⟩ rw [h,link_rows cap edge,List.map_map] apply List.map_congr_left intro row _; simp theorem row_head {a : Nat} {w row : W} (h : row ∈ rows a w) : row.head? = some a := by induction 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 := by induction w with | nil => rfl | cons x w ih => by_cases eq : x=a · subst x have 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 := by have non : rows b w ≠ [] := by intro z; have h := rows_length b w; rw [z,cb] at h; simp at h; omega obtain ⟨z,hz⟩ := List.exists_mem_of_ne_nil _ non induction pre generalizing a with | nil => have e : rows a w = rows b w := by simpa using eq have 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 ma subst c let next := p.head?.getD b have all (v) (hv : v ∈ rows b w) : (p ++ v).head? = some next := by cases p with | nil => simpa [next] using row_head hv | cons x xs => rfl have ct : w.count a = r := by simpa [rows_length,cb] using congrArg List.length eq have li : Link r w a next := by apply Eq.trans _ ct; apply all_next intro t ht rw [eq] at ht obtain ⟨v,hv,rfl⟩ := List.mem_map.mp ht exact all v hv apply prepend li apply ih have strip := congrArg (List.map List.tail) ((link_rows cap li).symm.trans eq) simpa [List.map_map,Function.comp_def] using strip theorem directed_joined {e a b} (p : Directed e a b) : Joined e a b := by induction 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 := by induction 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 := by induction q with | refl => exact p | extend _ t j => exact .extend j t exact cat (.extend (.refl _) (.inr last)) ih theorem project_rows (keep : W) {a : Nat} (ha : a ∈ keep) (w : W) : rows a (select keep w) = (rows a w).map (select keep) := by induction 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 := by induction 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 b apply congrArg (List.cons a) apply ih intro c d by_cases ac : a = c <;> by_cases ad : a = d <;> simpa [select,ac,ad] using pairs c d theorem rowmaps_ext {as bs : List W} (pairs : ∀ c d : Nat, as.map (select [c,d]) = bs.map (select [c,d])) : as = bs := by induction 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 := by induction 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 ++ ·) := by simp [List.map_map, Function.comp_def, select, List.filter_append] /-- A putative merger in every extension of some two extra names recovers 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 := by have ma : A ∈ rows a w := by simp [aa] have mb : B ∈ rows b w := by simp [bb] have headA := row_head ma have headB := row_head mb have pre_head : pre.head? = some a := by cases pre with | nil => simp_all | cons x p => simpa [first] using headA apply directed_of_prefix hr cp cb pre apply rowmaps_ext intro c d obtain ⟨keep,ha,hb,hc,hd,sm⟩ := merges c d have not_empty : select keep pre ≠ [] := by cases pre with | nil => contradiction | cons x p => have eq : x=a := by simpa using pre_head simp [select,eq,ha] have rx := project_rows keep ha w have ry := project_rows keep hb w have capK := P455DefectProjection.select_cap keep cp have hdir := directed_of_same hr capK sm have orient' : ∃ k : W, rows a (select keep w) = (rows b (select keep w)).map (k ++ ·) := by rcases hdir with f|g · exact directed_prefix capK f · obtain ⟨k,h⟩ := directed_prefix capK g rw [rx,ry,aa,bb] at h have eq := (List.cons.inj h).1 have len := congrArg List.length eq simp only [first,select_append,List.length_append] at len have pos := List.length_pos_iff.mpr not_empty omega obtain ⟨k,h⟩ := orient' rw [rx,ry] at h have fst := h rw [aa,bb] at fst have eq := (List.cons.inj fst).1 change select keep A = k ++ select keep B at eq rw [first,select_append] at eq have := List.append_cancel_right eq subst k rw [← project_prefix] at h let 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) h simpa only [List.map_map, Function.comp_def,nested] using proj theorem 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 := by classical apply Classical.byContradiction intro contra have merges : ∀ c d : Nat, ∃ keep : W, a ∈ keep ∧ b ∈ keep ∧ c ∈ keep ∧ d ∈ keep ∧ SameBlock r (select keep w) a b := by intro c d apply Classical.byContradiction; intro miss apply contra; refine ⟨c,d,?_⟩ intro keep ha hb hc hd hm exact miss ⟨keep,ha,hb,hc,hd,hm⟩ have oba : occ a w = r := (Problem455BlockBridge.occ_count ..).trans ca have obb : occ b w = r := (Problem455BlockBridge.occ_count ..).trans cb have ne : a ≠ b := by rintro rfl; exact apart ⟨oba,obb,.refl _⟩ apply apart refine ⟨oba,obb,?_⟩ have split (z : Nat) (cz : w.count z = r) : ∃ h t, rows z w = h::t := by cases 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 ca obtain ⟨B,Bs,bb⟩ := split b cb rcases 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 d obtain ⟨keep,ha,hb,hc,hd,m⟩ := merges c d refine ⟨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 g end P455BlockSeparators end /- Begin Problem455FirstTesters (from finite-semigroup-identity-bases). -/ section namespace P455FirstTesters open P455FirstRewrite P455Quotient def plain (r : Nat) : Rules Nat where r := r step := fun _ _ => False reverse := False.elim counts := False.elim extend := False.elim def power (r : Nat) : W := List.replicate r 0 def 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 := by rcases i.property with e | b · intro x; rw [e,power,List.count_replicate]; split <;> simp [plain] · exact b.2.1 private theorem binary_length {T : W} (letters : ∀ x ∈ T, x = 0 ∨ x = 1) : T.length = T.count 0 + T.count 1 := by induction 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] <;> omega theorem index_covered {r : Nat} (i : Index r) : i.val ∈ Problem455Finite.wordsUpTo [0, 1] (2*r) := by apply Problem455Finite.covered · rcases i.property with e | b · rw [e,power,List.length_replicate]; omega · have cnt := binary_length b.1 have l := b.2.1 0 have h := b.2.1 1 omega · intro x m rcases i.property with e | b · rw [e] at m; have := List.eq_of_mem_replicate m; simp_all [power] · simpa using b.1 x m abbrev Carrier (r : Nat) := (i : Index r) → Q (plain r) i.val def product (r : Nat) : Model (Carrier r) where op := 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) := by let 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) := by induction 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]; rfl exact (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 := by have good : Good (plain r) T A := ⟨T,.refl T,factor⟩ have path := ((same_nonzero_class (plain r) good).mp eq).2 induction path with | refl => rfl | snoc _ f _ => exact False.elim f def 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) := by induction 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 := by let i : Index r := ⟨power r,Or.inl rfl⟩ have eq := observed h i (unaryImage x) simp only [unary_word] at eq have fac : Factor (power (u.count x)) (power r) := by refine ⟨[], power (r-u.count x), ?_⟩ simp only [List.nil_append,power,List.replicate_append_replicate] congr 1; omega simpa [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 := by obtain ⟨y,_,m⟩ := List.mem_flatMap.mp m unfold code at m split at m · exact Or.inl (List.mem_singleton.mp m) · split at m · exact Or.inr (List.mem_singleton.mp m) · simp at m private 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 := by induction 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 := by induction 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 := by induction 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 := by simp only [proj,Or.comm] private theorem identical_letter (i : Nat) (w : W) : proj i i w = List.replicate (w.count i) i := by induction 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 actual clipped 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 := by have clipped (x) : min (u.count x) (r+1) = min (v.count x) (r+1) := by by_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] · omega refine ⟨clipped,?_⟩ intro cu cv i j diff have counts (x) : u.count x = v.count x := by have := clipped x; have := cu x; omega have ne : i ≠ j := by intro 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 := by apply Nat.pos_of_ne_zero; intro zero; apply d have zv : v.count b = 0 := (counts b).symm.trans zero rw [only_one u (List.count_eq_zero.mp zero),only_one v (List.count_eq_zero.mp zv),counts] have pj := positive i j diff have pi := positive j i (by simpa only [proj_swap j i] using diff) apply Classical.byContradiction intro fail have low : u.count i < r ∨ u.count j < r := by have := cu i; have := cu j; omega let T := u.flatMap (code i j) obtain ⟨c0,c1⟩ := code_counts i j ne u have letters := code_letters i j u have cap : Cap r T := by intro x by_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]; omega let 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 eq dsimp [T] at ee apply diff rw [← decode i j u,← decode i j v,ee] /-- Extra components of the final direct product are arbitrary. Including the unmarked testers forces their consequences for every valid multiplication identity. -/ def combine {A B : Type} (M : Model A) (N : Model B) : Model (A × B) where op := 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 := by intro f let g := fun x => (f x,N.unit) have fst (w : W) : ((combine M N).eval g w).1 = M.eval f w := by induction w with | nil => rfl | cons x t ih => exact congrArg (M.op (f x)) ih exact (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 valid end P455FirstTesters end /- Begin Problem455Schedule (from finite-semigroup-identity-bases). -/ section namespace P455Schedule abbrev Edges := Nat → Nat → Prop abbrev Bits := Nat → Bool inductive 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 z def induced (C : List Nat) (E : Edges) : Edges := fun a b => a ∈ C ∧ b ∈ C ∧ E a b def Acyclic (C : List Nat) (E : Edges) := ∀ a, ¬Path (induced C E) a a def Good (C : List Nat) (E : Edges) (s : Bits) := ∀ a b, E a b → (a ∈ C ∨ b ∈ C) → s a = true → s b = true def 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 b def Down (C : List Nat) (E : Edges) (available : Nat → Prop) (s t : Bits) := Flip C E available s t ∧ ∀ a, t a = true → s a = true def meet (A B : Bits) : Bits := fun a => A a && B a private 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 := by induction xs with | nil => exact (ne rfl).elim | cons x xs ih => by_cases emp : xs = [] · subst xs refine ⟨x,List.mem_cons_self,?_⟩ intro b hb obtain rfl := List.mem_singleton.mp hb exact no b obtain ⟨a,mem,first⟩ := ih emp by_cases e : R x a · refine ⟨x,List.mem_cons_self,?_⟩ intro b hb rcases 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 hb rcases List.mem_cons.mp hb with eq|hit · exact eq ▸ e · exact first b hit private 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 := by classical by_cases empty : todo = [] · have eq : s = t := by funext a; apply Classical.byContradiction; intro diff exact 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 empty obtain ⟨ac,ch,sa,ta⟩ := all a am let v : Bits := fun j => if j=a then false else s j have 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 := by intro i j edge touch on have si : s i = true := by by_cases eq : i = a · subst i; simp [change] at on · exact (fixed i eq).symm.trans on by_cases eq : j = a · subst j have off : t i = false := by cases e : t i with | false => rfl | true => have impossible := tOK i a edge (.inr ac) e; simp [ta] at impossible have 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 := by refine ⟨⟨sOK,vOK,a,ac,ch,by simp [sa,change],fun j ne => (fixed j ne).symm⟩,?_⟩ intro j h by_cases eq : j=a · subst j; simp [change] at h · exact (fixed j eq).symm.trans h have next (j) (hj : j ∈ todo.erase a) : j ∈ C ∧ available j ∧ v j = true ∧ t j = false := by obtain ⟨ne,hit⟩ := uniq.mem_erase_iff.mp hj obtain ⟨h1,h2,h3,h4⟩ := all j hit exact ⟨h1,h2,(fixed j ne).trans h3,h4⟩ have rem (j) (diff : v j ≠ t j) : j ∈ todo.erase a := by by_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 rem exact (P455Quotient.Walk.snoc (.refl _) single).trans tail termination_by todo.length decreasing_by have n := List.length_erase_of_mem am have pos : 0 < todo.length := List.length_pos_iff.mpr empty omega private 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) := by let todo := (P455FirstRewrite.names C).filter (fun a => A a && !B a) have inTodo (a) : a ∈ todo ↔ a ∈ C ∧ A a = true ∧ B a = false := by simp [todo,P455FirstRewrite.mem_names] have ok : Good C E (meet A B) := by intro i j edge hit h obtain ⟨a,b⟩ := Bool.and_eq_true_iff.mp h exact 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 ha obtain ⟨hc,h1,h2⟩ := (inTodo a).mp ha exact ⟨hc,⟨h1,h2⟩,h1,by simp [meet,h2]⟩ · intro a diff cases ha : A a <;> cases hb : B a <;> simp [meet,ha,hb] at diff exact (inTodo a).mpr ⟨fixed a (by simp [ha,hb]),ha,hb⟩ /-- Explicit two phases. Within each phase every changed vertex moves in a single 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) := by have 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 t private 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 := by induction 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 := by induction h with | refl => exact .refl _ | snoc _ m ih => exact (P455Quotient.Walk.snoc (.refl _) m).trans ih theorem 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 := by obtain ⟨lhs,rhs⟩ := phases acy A B gA gB fixed apply (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) (by intro s t st obtain ⟨⟨ok1,ok2,a,hc,ab,ne,unch⟩,down⟩ := st have ons : s a = true := by cases h : s a <;> cases k : t a <;> simp_all exact ⟨ok2,ok1,a,hc,ons.trans ab.1.symm,Ne.symm ne,fun j h => (unch j h).symm⟩)) · intro s t st obtain ⟨⟨ok1,ok2,a,hc,ab,ne,unch⟩,down⟩ := st have off : t a = false := by cases h : s a <;> cases k : t a <;> simp_all exact ⟨ok1,ok2,a,hc,off.trans ab.2.symm,ne,unch⟩ /-- Realizing the safe Boolean singletons by bounded-rank word steps produces an 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) := by have 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) := by induction path with | refl => exact .refl _ | snoc _ move ih => exact .snoc ih (one _ _ move) exact lift (schedule acy A B gA gB fixed) end P455Schedule end /- Begin Problem455EffectiveMachineCode (from finite-semigroup-identity-bases). -/ section /- Explicit finite instruction arrays for the machines of the reduction. -/ namespace P455EffectiveMachine open P455MachineLocal P455MachineCleanup structure Code (g q : Nat) where marker : Fin g blank : Fin g start : Fin q rows : Vector (Vector (Option (Ins (Fin g) (Fin q))) g) q def Code.read (C : Code g q) (s : Fin q) (a : Fin g) := (C.rows.get s).get a def 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) := by let 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 i have mem : i∈List.finRange n := by have bound : i.val < (List.finRange n).length := by simp simpa 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 := by let 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) := by unfold p; split <;> infer_instance letI 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_instance def Code.machine (C : Code g q) (v : C.Safe) : Ordinary g q where marker := C.marker blank := C.blank blank_ne := v.1 start := C.start delta := C.read keeps := by intro s a i e have h := v.2 s a rw [e] at h exact h.1 leftSafe := by intro s i e have h := v.2 s C.marker rw [e] at h exact h.2 rfl def Code.decode (C : Code g q) : Option (Ordinary g q) := if h : C.Safe then some (C.machine h) else none def 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 := by simp [Code.read,quote,Vector.get] theorem safe_quote (M : Ordinary g q) : (quote M).Safe := by refine ⟨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 := by rw [Code.decode,dif_pos (safe_quote M)] congr 1 have 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 := by cases X; cases Y; simp_all exact 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 public machine-code payload. 0 is an undefined instruction. 1+3*(g*s+a)+d codes a next state s, write symbol a and direction d (left/stay/right). -/ def dirCode : Direction → Nat | .left => 0 | .stay => 1 | .right => 2 def 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.dir def 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 unary end P455EffectiveMachine end /- Begin Problem455SourceTheorem (from finite-semigroup-identity-bases). -/ section namespace P455SourceTheorem open P455Witness P455Paths P455ContactLift P455SourceFamilies P455PortReflection open P455EdgeSource P455Retained P455OriginalWalk Problem455.Slots def 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.a if mate then n.mate else n.owner def 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 e def 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 := by cases 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) := by cases 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 is transported 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) := by obtain ⟨z,l,k,path,eq,ok⟩ := arbitrary_reps_designated capT val v h reps live c ts initial subst z have cap : P455Closure.Cap r (l ++ v.flatMap h ++ k) := fun s => (P455Quotient.count_walk _ path s) ▸ capT s exact ⟨_,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 r Holds r allow (sourceMarks d c) (v.flatMap e) ((transferred d c).query r ts) := by let d := donor v h r have pos : 0 < r := by omega cases c with | edge ed => exact P455OriginalEdges.expand_edge exp hr capU ev | functionality f => obtain ⟨bit,b,c,dist,_⟩ := ev exact ⟨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,_⟩ := ev have eq : d (picked s) = seed := donor_eq pos capF start have big := exp.walk hr capU _ _ walk let m := markNode (sendNode d s.anchor) let finalLabel := endpoint (picked s) s.steps have ep : endpoint seed (relabel d s.steps) = d finalLabel := by rw [← eq,endpoint_relabel] have pickEq : picked (sendSlot d s) = d (picked s) := by cases z : s.startAtMate <;> simp [picked,sendSlot,sendNode,z] obtain ⟨len,_,termT⟩ := slot_route s initial have valid := valid_slot s.defect termT have bigWalk : Walk r allow mark (v.flatMap e) seed (relabel d s.steps) := remark_walk _ _ big have 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).1 have 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 := by have present : y ∈ v := List.count_pos_iff.mp (by omega) have ky : kept y := by apply Classical.byContradiction intro absent have := (exp.gaps y present absent).1 omega have mem : y ∈ e y := by rw [exp.literal y present ky]; simp exact ⟨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 terminal refine ⟨P455OriginalEdges.expand_markedNode exp hr capU bit,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩ apply (route_iff ..).mpr change 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 h in the smaller word v. Independently e expands the fresh gaps of v to the original 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 r let u := v.flatMap e let 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) := by obtain ⟨z,l,k,path,eq,ok,source,_⟩ := arbitrary_reps_source_gadget capT val v h reps live ts c initial second mate seed (by omega) start (exp.guard hr capU original) subst z have cap : P455Closure.Cap r (l ++ v.flatMap h ++ k) := fun s => (P455Quotient.count_walk _ path s) ▸ capT s exact ⟨_,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 P455SourceTheorem end /- Begin Problem455SmallRank (from finite-semigroup-identity-bases). -/ section namespace P455SmallRank open P455Closure P455Compression P455Uncrossed open 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 t private def gaps (n : Nat) : List Piece → W | [] => [] | .literal _ :: t => gaps (n+1) t | .gap _ :: t => n :: gaps (n+1) t private 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 => by have := gap_bound (n+1) cs ok simpa [gaps,lits] using Nat.le_step this | [.gap _],_ => by simp [gaps,lits] | .gap _ :: .literal _ :: cs,ok => by have h := gap_bound (n+1+1) cs ok simp only [gaps,lits,List.length_cons] omega | .gap _ :: .gap _ :: _,ok => False.elim ok private theorem lit_subset (cs : List Piece) : (lits cs).Sublist (cs.flatMap body) := by induction 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 := by induction 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 := by induction 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 tail private theorem count_away (a : Nat) (w : W) : w.length = w.count a + (w.filter (· != a)).length := by induction w with | nil => rfl | cons b w ih => by_cases e : b = a <;> simp [e,List.count_cons] <;> omega private theorem length_bound (r : Nat) (C w : W) (cap : Cap r w) (covered : ∀ a ∈ w, a ∈ C) : w.length ≤ r*C.length := by induction 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_sublist have ht : Cap r t := fun b => Nat.le_trans (subset.count_le b) (cap b) have tc (b) (hb : b ∈ t) : b ∈ C := by obtain ⟨bw,ba⟩ := List.mem_filter.mp hb exact (List.mem_cons.mp (covered b bw)).resolve_left (by simpa using ba) have h := ih t ht tc have split := count_away a w have c := cap a simp only [List.length_cons,Nat.mul_succ] dsimp [t] at h; omega private theorem literal_bound {r : Nat} (u keep : W) (cap : Cap r u) : (lits (pieces keep u)).length ≤ r*(names keep).length := by have sub := lit_subset (pieces keep u) rw [decoded] at sub apply 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 := by induction 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 := by have l := literal_bound u keep cap have 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 := by let cs := pieces keep u let n := base u keep have l := literal_bound u keep cap have g := gap_bound n cs (maximal keep u) have le : rank (small u keep) v ≤ ((names keep) ++ gaps n cs).length := by apply size_le (names_distinct _) intro a ha have ma := (List.mem_append.mp ((mem_names _ _).mp ha)).elim id (same a) have mem := cover keep n cs (pieces_good keep u) a ma exact List.mem_append.mpr (mem.imp_left (mem_names a keep).mpr) simp only [List.length_append] at le dsimp only [cs] at g; dsimp only [cs] at le; omega private theorem lookup_nonempty (keep : W) (cs : List Piece) (all : ∀ c ∈ cs,good keep c) (n a : Nat) : lookup n cs a ≠ [] := by induction 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 on at most N + r*N + 1 variables. All substitution images, even for unused variables, 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).length Step (fun u v => M.Valid u v ∧ rank u v ≤ N+r*N+1) (side f l k b) (side f l k (!b)) := by dsimp only obtain ⟨g,left,right,gp,_,_,eq,expanded⟩ := P455CompressedFrame.canonical_pair f l k keep hx hy hp hq valid b cap have letters (a) (ha : a ∈ small (side f l k (!b)) keep) : a ∈ small (side f l k b) keep := by rw [eq] at ha ⊢ exact (P455Uncrossed.same_letters g left right b a).mpr ha have nonempty (c : Bool) : small (side f l k c) keep ≠ [] := by rw [eq]; obtain ⟨t,e⟩ := g.core_starts c simp [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 P455SmallRank end /- Begin Problem455OtherProjection (from finite-semigroup-identity-bases). -/ section namespace P455OtherProjection open P455Witness P455Paths P455SourceFamilies P455PortReflection P455DefectProjection Problem455.Slots open Problem455Swap (SameBlock) def Covers (keep xs : W) := ∀ a ∈ xs, a ∈ keep private 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 := by induction 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 hb rcases 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 hx theorem 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) := by induction xs with | nil => exact ⟨[],by simp,by simp⟩ | cons a xs ih => obtain ⟨ds,pw⟩ := List.pairwise_cons.mp diff have st (b) (h : b ∈ xs) := sat b (by simp [h]) obtain ⟨xs₁,n₁,k₁⟩ := fan hr cp a xs (sat a (by simp)) st ds obtain ⟨xs₂,n₂,k₂⟩ := ih st pw refine ⟨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 more have 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 := by induction p generalizing a with | nil => exact ct | cons bc p ih => obtain ⟨b,c⟩ := bc apply ih b _ walk.2 cases 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.1 theorem 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) := by let a := picked s let t := endpoint a s.steps obtain ⟨bound,walk,term⟩ := slot_route s ok rw [kind] at term obtain ⟨len,diff,all,_⟩ := term have 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 := by cases side : s.startAtMate <;> simp [a,picked,side,ct] have termCount := walk_count cap a s.steps start walk have st : ∀ b ∈ t::xs, u.count b = r := by intro b h; rcases List.mem_cons.mp h with rfl|h · exact termCount · exact (members b h).1 obtain ⟨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 path have 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 len simp only [List.length_cons,len] at n simp [keep,len] omega · apply (route_iff ..).mpr refine ⟨select_walk keep a s.steps pickedKept path walk,?_⟩ rw [kind] refine ⟨len,(P455TerminalTransfer.block_separation _).mpr allSep,?_,True.intro⟩ apply (allQ_iff _).mpr intro q hq; obtain ⟨b,h,rfl⟩ := List.mem_map.mp hq have m := members b h exact ⟨(select_count keep u b (keptOcc b h)).trans m.1,m.2.1,select_slot keep t _ b last (keptOcc b h) m.2.2⟩ 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) := by apply (earlyBefore_iff _ _).mpr intro a ha b hb apply 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) := by have 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,_⟩ := obs refine ⟨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) := by have 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) := by obtain ⟨anchor,nb,nc,apart,_⟩ := ok let role := roleOf f.distinguishMate have sat (n : Node) (obs : Holds r allow (markNode f.anchor) u (neighbor ts f.anchor n f.dir)) : u.count (role n) = r := by have 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) apart let names := roles f.anchor ++ roles f.b ++ roles f.c let keep := x::y::names have 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 := by apply h cases 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 P455OtherProjection end /- Begin Problem455StructuralWords (from finite-semigroup-identity-bases). -/ section namespace P455Structural open P455Witness P455Quotient P455Closure P455Uncrossed Problem455.Slots open P455SourceFamilies P455FirstTesters abbrev W := List Nat def 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 a def Width (k : Nat) (T : W) := ∃ C : W, C.length ≤ k ∧ ∀ x ∈ T, x ∈ C def 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 q def 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 ∉ L private theorem only_z (x z : Nat) (L : W) (nx : x ∉ L) : select [x,z] L = List.replicate (L.count z) z := by induction 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 := by obtain ⟨ab,L,R,rfl,na,nb⟩ := closed refine ⟨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 := by cases 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 := by obtain ⟨n,tail,eq⟩ := early_projection closed inside out have nz : x ≠ z := by omega rintro (⟨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)] := by obtain ⟨ab,L,R,rfl,na,nb⟩ := closed intro obs have no : o ∉ L := oi.elim (fun e => e ▸ na) (fun e => e ▸ nb) have cp : (early a b).count p = 3 := by rcases 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) R have h : [(o,0),(z,j),(p,2)].Sublist (events L ++ (inner ++ right)) := by simpa only [sees,events_of_factor,inner,right] using obs have nl : (o,0) ∉ events L := fun m => no (stamped_mem_label _ _ _ m) have nr : (p,2) ∉ right := by intro m have low := (P455ContactGeometry.stamp_range (fun x => L.count x + (early a b).count x) R m).1 omega have strip {α : Type} (x : α) (pat u v : List α) (nx : x ∉ u) (sub : (x::pat).Sublist (u++v)) : (x::pat).Sublist v := by induction 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).reverse simp only [List.reverse_append,List.reverse_cons,List.reverse_nil,List.nil_append,List.cons_append] at h1 have h2 := (strip _ _ right.reverse inner.reverse (by simpa using nr) h1).reverse have 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 mid have ze : e.1 = z := congrArg Prod.fst eq have is := stamped_mem_label _ _ _ me simp [early,ze,out.1,out.2] at is private theorem rec_mem {T r allow a b} (h : Rec T r allow a b) : a ∈ T ∧ b ∈ T := by obtain ⟨t,_,_,_,bit,eq⟩ := h have f (x : Nat) (hx : x=a ∨ x=b) : x ∈ T := by have mm : x ∈ profile a b t bit := by rcases hx with rfl|rfl <;> simp [profile,profilePrefix] rw [← eq] at mm exact (List.mem_filter.mp mm).1 exact ⟨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 := by obtain ⟨_,l,t,rfl,_,_⟩ := h simp [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) := by constructor · intro h apply Classical.byContradiction; intro n exact no_external_record c h ⟨fun e => n (.inl e),fun e => n (.inr e)⟩ edge · intro h apply Classical.byContradiction; intro n exact no_external_record c h ⟨fun e => n (.inl e),fun e => n (.inr e)⟩ edge.symm theorem structural_excludes_closed {r allow T a b} (stest : Structural T r allow) (c : Closed T a b) : False := by obtain ⟨ma,mb⟩ := closed_mem c have ab := c.1 rcases stest with ⟨⟨C,len,Cmem⟩,o,p,q,op,oq,pq,e1,e2⟩|⟨⟨C,len,Cmem⟩,o,p,z,j,op,zo,zp,rec',seen⟩ · have linkP := separated_core c e1 have linkQ := separated_core c e2 by_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 e2 have uniq : [a,b,o,p,q].Nodup := by simp [List.nodup_cons]; omega have sub (x) (m : x ∈ [a,b,o,p,q]) : x ∈ C := by simp only [List.mem_cons,List.not_mem_nil,or_false] at m rcases m with rfl|rfl|rfl|rfl|rfl <;> apply Cmem <;> simp_all have := P455FirstRewrite.size_le uniq sub simp 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 h apply early_bound c h hp _ seen omega · have A := rec_mem rec' have uniq : [a,b,o,p].Nodup := by simp [List.nodup_cons]; omega have sub (x) (m : x ∈ [a,b,o,p]) : x ∈ C := by simp only [List.mem_cons,List.not_mem_nil,or_false] at m rcases m with rfl|rfl|rfl|rfl <;> apply Cmem <;> simp_all have := P455FirstRewrite.size_le uniq sub simp at this; omega end P455Structural end /- Begin Problem455RectangleRank (from finite-semigroup-identity-bases). -/ section namespace P455RectangleRank open P455FirstRewrite def owner (i : Nat) := 2*i def mate (i : Nat) := 2*i+1 def 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) ++ tail def constant (b : Bool) : Nat → Bool := fun _ => b private theorem within {t i : Nat} (m : i ∈ List.range t) {x : Nat} (member : x = owner i ∨ x = mate i) : x < 2*t := by have := List.mem_range.mp m unfold owner mate at member omega theorem 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 := by simp only [word,List.mem_append,List.mem_flatMap] at hx rcases hx with ((⟨i,mi,m⟩|m)|⟨i,mi,m⟩)|m · apply within mi simp only [privateCell,List.mem_cons,List.mem_nil_iff,or_false] at m rcases m with h|h|h|h|h|h <;> simp [h] · exact small x (List.mem_append_left _ m) · apply within mi unfold mutableCell at m split 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) := by obtain ⟨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 word conv => 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 := by obtain ⟨p,q,rfl⟩ := factor rw [Problem455Swap.bigram_append,Problem455Swap.bigram_append] omega theorem 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) := by let U := word t middle tail bit intro x y link change Problem455Swap.bigram x y U = r at link have bound := Problem455Swap.out_bound x y (y+1) (by omega) U rw [Problem455BlockBridge.occ_count] at bound have mem : x ∈ U := List.count_pos_iff.mp (by omega) have smallX := word_names bit small x mem let i := x/2 have ix : i < t := by dsimp [i]; omega have either : x = owner i ∨ x = mate i := by simp only [owner,mate,i]; omega have ne : owner i ≠ mate i := by simp [owner,mate] have fac := private_factor ix middle tail bit have aPos : 0 < Problem455Swap.bigram x (owner i) U := by apply positive_factor fac rcases either with e|e <;> conv => rhs; arg 1; rw [e] all_goals simp [privateCell,Problem455Swap.bigram,Problem455Swap.hit,ne,Ne.symm ne] <;> omega have bPos : 0 < Problem455Swap.bigram x (mate i) U := by apply positive_factor fac rcases either with e|e <;> conv => rhs; arg 1; rw [e] all_goals simp [privateCell,Problem455Swap.bigram,Problem455Swap.hit,ne,Ne.symm ne] <;> omega obtain ⟨z,ny,pz⟩ : ∃ z, y ≠ z ∧ 0 < Problem455Swap.bigram x z U := by by_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 U rw [Problem455BlockBridge.occ_count] at upper have cx : U.count x ≤ r := cap x omega private 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 []) := by induction cells with | nil => rfl | cons j t ih => have tail := ih (List.nodup_cons.mp nd).2 by_cases e : i=j · subst j have out := (List.nodup_cons.mp nd).1 have one : proj (owner i) (mate i) (mutableCell bit i) = mutableCell bit i := by cases 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 := by unfold owner mate; omega have no : proj (owner i) (mate i) (mutableCell bit j) = [] := by cases 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)) := by intro x m have lt := List.mem_range.mp m let i := x/2 have 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)) := by intro eq simp only [word,proj,List.filter_append,List.append_cancel_right_eq,List.append_cancel_left_eq] at eq change 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 eq rw [project_mutable _ List.nodup_range,project_mutable _ List.nodup_range] at eq simp [mi,mutableCell,constant,owner,mate] at eq have either : x = owner i ∨ x = mate i := by simp only [owner,mate,i]; omega rcases 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 a constant 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 := by have onward (i j : Nat) (le : i ≤ j) (lt : j < t) (yes : bit i = true) : bit j = true := by induction 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⟩ := existsTrue have 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) := by have m : (List.range t).flatMap (mutableCell bit) = (List.range t).flatMap (mutableCell (constant b)) := by have go (xs : W) (small : ∀ i ∈ xs, i < t) : xs.flatMap (mutableCell bit) = xs.flatMap (mutableCell (constant b)) := by induction 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, representation of every identical word by cell bits, and detection of each descending snake (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)) := by have m0 : 0 ∈ List.range (2*t) := List.mem_range.mpr (by omega) obtain ⟨y,change0⟩ := participants middle tail 0 m0 have 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 ≠ [] := by obtain ⟨p,q,eq⟩ := private_factor (i:=0) ht middle tail bit rw [eq]; simp [privateCell] refine ⟨⟨nonempty _,nonempty _⟩,ne,identity,?_,cap,no_links hr _ small cap, List.nodup_range,participants middle tail⟩ intro w valid obtain ⟨bit,rfl⟩ := represent w valid obtain ⟨nx,wrap⟩ := edge bit valid obtain ⟨b,all⟩ := cycle_constant bit nx wrap cases 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 P455RectangleRank end /- Begin Problem455EffectiveMachineDiagonal (from finite-semigroup-identity-bases). -/ section /- A diagonal argument for actual deterministic finite-control one-head machines. Input is a finite Boolean word over two tape symbols. -/ namespace P455EffectiveMachine open P455MachineLocal P455MachineCleanup P455MachineTable structure Alphabet (M : Ordinary g q) where bit : Bool → Fin g away : ∀ b, bit b ≠ M.marker ink : ∀ b, bit b ≠ M.blank distinct : bit false ≠ bit true /-- Position zero holds the permanent marker. Input occupies positions 1 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.bit def 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)=none def selfBits (M : Ordinary g q) (A : Alphabet M) : List Bool := unary (A.bit false).val ++ unary (A.bit true).val ++ (quote M).bits def 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 := by have tape : inputTape M A [] = fun x => if x=0 then M.marker else M.blank := by funext 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 := by induction 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 := by simp 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 := by induction 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 := by by_cases le : a≤b · have e := rest M c ha (b-a) rw [show a+(b-a)=b by omega] at e exact e.symm · have e := rest M c hb (a-b) rw [show b+(a-b)=a by omega] at e exact e def trap (M : Ordinary g q) (answer : Fin q → Bool) : Ordinary g q where marker := M.marker blank := M.blank blank_ne := M.blank_ne start := M.start delta := fun s a => match M.delta s a with | some i => some i | none => if answer s then some ⟨s,a,.stay⟩ else none keeps := by intro s a i eq cases 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 eq split at eq <;> simp_all <;> subst i <;> simp leftSafe := by intro s i eq cases 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 eq split at eq <;> simp_all <;> subst i <;> simp def 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 := by funext 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 := by cases 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 := by induction 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 := by cases 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 := by constructor · rintro ⟨i,hi⟩ rw [follow_trap,stop_trap] at hi exact unique_halt M c hi.1 ended ▸ hi.2 · intro h exact ⟨t,by rw [follow_trap,stop_trap]; exact ⟨ended,h⟩⟩ /-- A decider may have any finite work alphabet and arbitrary finite control. On the code of a binary-input machine it must halt and its Boolean output is read from the final control state. No behavior on ill-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 := by intro correct let P := trap D answer let B := liftAlphabet D A answer let c := inputConfig D A (selfBits P B) have same : inputConfig P B (selfBits P B)=c := rfl obtain ⟨t,halt,ok⟩ := correct P B change instruction D (follow D c t)=none at halt change (answer (follow D c t).state=true ↔ HALT P (inputConfig P B (selfBits P B))) at ok rw [same] at ok have contradiction := ok.trans (halt_trap_iff D answer c halt) cases e : answer (follow D c t).state <;> simp [e] at contradiction end P455EffectiveMachine end /- Begin Problem455CrossedSupport (from finite-semigroup-identity-bases). -/ section /- The guard used for a crossed flip is constructed from the two actual source names. The remaining geometric premise concerns only the counts of literal original-slot occupants in the indicated radius. -/ namespace P455CrossedSupport open P455Witness P455Paths P455ContactLift P455SourceFamilies open P455OriginalWalk P455SourceTheorem Problem455.Slots def 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 ++ k theorem 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 := by obtain ⟨f,b,l,k,hp,hq,v,rfl⟩ := flip have one (a : Nat) (mem : a ∈ f.p ∨ a ∈ f.q) : (l ++ f.core b ++ k).count a = r := by have sat := v.2.2.2.2.2.2.2 a mem have bit : (f.core b).count a = r := by cases b <;> first | exact sat | exact (f.count_core a true).trans sat have bound := cap a; simp only [List.count_append,bit] at bound ⊢; omega have 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 := by cases 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 := by rcases 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 6 def 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 = r def 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 affect membership. 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 := by classical exact 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 := by classical simp [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 := by induction p generalizing a with | nil => exact ha | cons step ps ih => obtain ⟨b,c⟩ := step have count := (P455Retained.contact_counts cap w.1).2 exact ih b (List.count_pos_iff.mp (count.symm ▸ hr)) w.2 theorem 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 := by intro t near have 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,_⟩ := near have ht := eq ▸ walked_name hr cap seed p hs w refine ⟨mem_retained.mpr ⟨ht,.inl ball⟩,?_⟩ intro i hi b between have inside : b ∈ u := by obtain ⟨j,events⟩ := between exact 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 P455CrossedSupport end /- Begin Problem455EdgeProjection (from finite-semigroup-identity-bases). -/ section namespace P455EdgeProjection open P455Witness P455Paths P455SourceFamilies P455CertificateReach P455PortReflection P455EdgeSource open P455DefectProjection P455OtherProjection P455DefectRename Problem455.Slots def 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.fst def names (ts : Tiles) (e : EdgeCertificate) := (nodes ts e).flatMap roles theorem nodes_exact {ts e n} : n ∈ nodes ts e ↔ Active ts e n := by constructor · intro h; obtain ⟨⟨j,b⟩,m,rfl⟩ := List.mem_map.mp h obtain ⟨cand,bok⟩ := List.mem_filter.mp m change b = true at bok; subst b simp only [candidates,List.mem_cons,List.not_mem_nil,or_false,Prod.mk.injEq, true_and,and_true] at cand rcases 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.symm exact .diagonal two.1 two.2 · intro active apply List.mem_map.mpr refine ⟨(_,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 := by simp [names,List.mem_flatMap,nodes_exact] theorem names_bound (ts : Tiles) (e : EdgeCertificate) : (names ts e).length ≤ 14 := by have rep (ls : List Node) : (ls.flatMap roles).length = ls.length * 2 := by induction ls with | nil => rfl | cons x ls ih => simp [roles,List.flatMap_cons,ih,Nat.add_mul, Nat.add_comm] at *; omega have bound : (nodes ts e).length ≤ 7 := by simpa [nodes,candidates] using (List.length_filter_le Prod.snd (candidates ts e)) rw [names,rep]; omega theorem 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 := by obtain ⟨n,ac,role⟩ := names_exact.mp mem have ct := record_counts cap (active_owner cap ts e ok ac).2 rcases (show x = n.owner ∨ x = n.mate by simpa [roles] using role) with rfl|rfl · exact ct.1 · exact ct.2 private 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) := by cases b · exact True.intro · exact transfer rfl h theorem 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) := by let keep := names ts e have ka : Covers keep (roles e.a) := covered .anchor have kb : Covers keep (roles e.b) := covered .successor have 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,_⟩ := ok refine ⟨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 b have 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 succ next 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 edge certificate 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 e let T := template ts e u P455Closure.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) := by let keep := names ts e let w := select keep u let T := template ts e u let d := keep.idxOf have hr : 0 < r := by have h : e.a.tag.length + 16 = r := ok.1.2.1; omega have 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 m have ext : w.map (extend keep) = T := extend_map small have 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 := by rw [← 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 hy exact ⟨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 := by have single (v : W) : v.flatMap h = v.map (decode keep) := by induction 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 small have uniform (n : Node) (ac : Active ts e n) : UniformOn r T h d (roles n) := by intro x hx; have k := covered ac x hx exact ⟨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 P455EdgeProjection end /- Begin Problem455Structural (from finite-semigroup-identity-bases). -/ section namespace P455Structural open P455Witness P455Quotient P455Closure P455Uncrossed Problem455.Slots open P455SourceFamilies P455FirstTesters private 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) := by induction 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]; omega private 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] := by cases 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) := by rw [z]; simp [Problem455Swap.bigram,Problem455Swap.hit] <;> omega have base := image_edge h x a b pair u have low : r ≤ Problem455Swap.bigram a b T := by rw [eq,Problem455Swap.bigram_append,Problem455Swap.bigram_append]; omega have top := Problem455Swap.out_bound a b (b+1) (by omega) T rw [Problem455BlockBridge.occ_count] at top have high := cap a exact 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 := by have h := P455DonorInterval.split_contributions h u x a simp [img,c] at h omega /-- Under any substitution, a live factor in a structural tester gives literal equality of the two substituted words. All other images may be empty 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 := by obtain ⟨pre,post,eq⟩ := fac have eqCore : T = (pre ++ l.flatMap h) ++ (f.core bit).flatMap h ++ (k.flatMap h ++ post) := by simpa [side,List.flatMap_append,List.append_assoc] using eq have count (z : Nat) (role : z = x ∨ z = y) : (f.core bit).count z = r := by have has : z ∈ f.p ∨ z ∈ f.q := by simpa [hp,hq] using role have orig := valid.2.2.2.2.2.2.2 z has cases bit with | false => exact orig | true => exact (f.count_core z true).trans orig have commute : h x ++ h y = h y ++ h x := by by_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)) nx obtain ⟨b,by'⟩ := singleton_in_template eqCore cap cmp (count y (.inr rfl)) ny by_cases ab : a=b · simp [ax,by',ab] exfalso apply structural_excludes_closed stest let L := pre ++ l.flatMap h have fresh (z s : Nat) (kind : z=x ∨ z=y) (im : h z = [s]) : s ∉ L := by have bound := cap s rw [eqCore] at bound have ct := image_count h (f.core bit) z s (count z kind) im apply List.count_eq_zero.mp dsimp [L] simp only [List.count_append] at bound ⊢ omega let tail := f.mid ++ f.beforeMutable ++ f.pair bit ++ f.beforeFinalP ++ f.p ++ f.beforeFinalQ ++ f.q have 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 := by obtain ⟨v,walk,fac⟩ := g have e : T=v := by induction walk with | refl => rfl | snoc _ impossible _ => exact False.elim impossible exact e ▸ fac /-- Universal equality in the actual Rees factor monoid of each structural template. Zero evaluations, either live orientation and arbitrary good representatives 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) := by classical apply Classical.byContradiction intro d let R := plain r have live : ∃ b : Bool, eval R cap val (side f l k b) ≠ zero R T := by by_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⟩ := live let u := side f l k b have 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 := by simpa only [h,dif_pos mem] using (existsRep a mem).choose_spec.2 have original := eval_rep R cap val u h rep have 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.symm end P455Structural end /- Begin Problem455PaddedPorts (from finite-semigroup-identity-bases). -/ section namespace P455PaddedPorts open P455RectangleRank Problem455.Slots abbrev W := List Nat inductive Block where | single (i : Nat) | pair (i j : Nat) deriving DecidableEq def cells : Block → W | .single i => [i] | .pair i j => [i,j] def phase (bs : List Block) := bs.flatMap fun b => cells b ++ cells b def roles (i : Nat) := [owner i,mate i] def letters (bs : List Block) := (phase bs).flatMap roles private theorem singleton_head {i j u : Nat} {p : W} (ne : i≠j) (eq : u :: u :: p = [i,j,i,j]) : False := by obtain ⟨rfl,e⟩ := List.cons.inj eq exact ne (List.cons.inj e).1 private 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 := by induction bs with | nil => simp [phase,select] at obs | cons b bs ih => change select [i,j] ((cells b ++ cells b) ++ phase bs) = _ at obs rw [select_append,select_append] at obs cases 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 obs exact (singleton_head ne obs).elim · have su : select [i,j] [u]=[] := by simp [select,hu] simp only [cells,su,List.nil_append] at obs exact 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 obs obtain ⟨rfl,rfl,_⟩ := obs exact 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 obs exact (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 obs exact (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 obs exact List.mem_cons_of_mem _ (ih obs) private theorem phase_mem (bs : List Block) (x : Nat) : x∈phase bs ↔ x∈bs.flatMap cells := by simp [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] := by obtain ⟨pre,post,eq⟩ := List.append_of_mem present subst bs change ((_ ++ (.pair i j :: post)).flatMap cells).Nodup at nd simp only [List.flatMap_append,List.flatMap_cons,cells,List.cons_append,List.nil_append] at nd have parts := List.pairwise_append.mp nd have hits (x : Nat) (m : x∈pre.flatMap cells) : x∉[i,j] := by intro e have no := parts.2.2 x m x (by simpa using List.mem_append_left (post.flatMap cells) e : x∈i::j::post.flatMap cells) exact no rfl have ends (x : Nat) (m : x∈post.flatMap cells) : x∉[i,j] := by have hi := (List.nodup_cons.mp parts.2.1).1 have hj := (List.nodup_cons.mp (List.nodup_cons.mp parts.2.1).2).1 intro e rcases (show x=i ∨ x=j by simpa using e) with rfl|rfl · exact hi (List.mem_cons_of_mem _ m) · exact hj m have 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 := by induction 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 eq have e : i=j := by have := eq.1; unfold owner at this; omega rw [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 := by induction 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 := by rcases 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 h have non : ∀ b∈roles a, b∉roles i ++ roles j := by intro b m n simp only [roles,List.cons_append,List.nil_append,List.mem_cons,List.not_mem_nil,or_false] at m n unfold owner mate at m n omega have erased := select_nil _ _ non have 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 := by unfold letters rw [role_selection,← phase_exact nd i j ne] change _ = [i,j,i,j].flatMap roles ↔ _ exact ⟨roles_inj,congrArg (List.flatMap roles)⟩ end P455PaddedPorts end /- Begin Problem455EffectiveMachinePrefix (from finite-semigroup-identity-bases). -/ section /- Compile a finite straight-line initialization script into ordinary finite control, preserving halting from arbitrary tapes and positions. -/ namespace P455EffectivePrefix open P455EffectiveMachine P455MachineLocal P455MachineTable P455MachineCleanup inductive Cmd (g : Nat) | right | left | putRight (v : Fin g) structure Env (g : Nat) where tape : Nat → Fin g pos : Nat def 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 | _ => a def motion (mark : Fin g) (cmd : Cmd g) (a : Fin g) : Direction := match cmd with | .left => if a=mark then .stay else .left | _ => .right def 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 := by cases cmd <;> simp [write] split <;> simp_all theorem safe_motion (mark : Fin g) (cmd : Cmd g) : motion mark cmd mark ≠ .left := by cases 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) where marker := M.marker blank := M.blank blank_ne := M.blank_ne start := head q delta s a := if h : s.val 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 _ _ _ e next => simp only [Option.some.injEq] at eq subst i; exact write_marker .. leftSafe := by intro s i eq split at eq next 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 _ _ e next => simp only [Option.some.injEq] at eq subst i; exact safe_motion M.marker cmd def 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 := by simp [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⟩ := by simp [push,head] theorem once_old (M : Ordinary g q) (cmd) (c : Config g q) : once (push M cmd) (liftConfig c)=liftConfig (once M c) := by cases 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) := by induction 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) := by constructor · rintro ⟨t,fin⟩ cases t with | zero => change (push M cmd).delta (head q) (e.tape e.pos)=none at fin simp [head_ins] at fin | succ t => refine ⟨t,?_⟩ rw [after_one] at fin simp only [instruction,liftConfig,old_ins,Option.map_eq_none_iff] at fin exact fin · rintro ⟨t,fin⟩ refine ⟨t+1,?_⟩ rw [after_one] simpa only [instruction,liftConfig,old_ins,Option.map_eq_none_iff] using fin def 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 := by induction cs with | nil => rfl | cons c cs ih => exact ih theorem installed_blank (M : Ordinary g q) (cs) : (install M cs).2.blank=M.blank := by induction cs with | nil => rfl | cons c cs ih => exact ih def perform (mark : Fin g) (cs : List (Cmd g)) (e : Env g) := cs.foldl (fun z c => effect mark c z) e theorem 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) := by induction 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 P455EffectivePrefix end /- Begin Problem455EffectiveMachineChain (from finite-semigroup-identity-bases). -/ section /- An executable finite-control composition of a tape transducer and a decision machine. The transition at the writer's terminal configuration changes control to the reader and leaves the entire tape unchanged. -/ namespace P455EffectiveChain open P455EffectiveMachine P455MachineLocal P455MachineCleanup P455MachineTable def 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 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)) := by have h : ¬ q+s.val 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 eq cases d : D.delta j a with | none => simp [d] at eq | some z => rw [d] at eq; obtain rfl := Option.some.inj eq exact mark ▸ D.keeps _ _ _ d leftSafe := by intro s i eq by_cases h : s.val 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 eq cases 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 _ _ d def 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 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⟩ := by change W.delta c.state (c.tape c.pos)=none at halt simp [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) := by cases 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 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) := by induction 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 := by induction k with | zero => rfl | succ k ih => exact congrArg (once M) ih theorem earliest (P : Nat→Prop) (t : Nat) (hit : P t) : ∃ j, P j ∧ ∀ i, i by_cases h : ∃ j, j 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) t instruction W c=none ∧ c.pos=0 ∧ c.tape=inputTape D B y def 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) t instruction D c=none ∧ ans c.state=v theorem 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 := by obtain ⟨t,atT,pos,tape⟩ := produces obtain ⟨k,stopped,verdict⟩ := reads let c := inputConfig W A x let C := chain W D mark obtain ⟨j,atJ,before⟩ := earliest (fun i => instruction W (follow W c i)=none) t atT have eq : follow W c j=follow W c t := unique_halt W c atJ atT have env : (⟨(follow W c j).tape,(follow W c j).pos,D.start⟩ : Config g r)=inputConfig D B y := by rw [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]; rfl let ini := inputConfig C (liftAlphabet W D mark A) x have ini_eq : ini=rename (left r) c := rfl have start : follow C ini (j+1)=rename (right q) (inputConfig D B y) := by rw [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) := by rw [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=v rw [final] constructor · simpa only [instruction,C,chain,rename,right_delta,Option.map_eq_none_iff] using stopped · exact (out_right ..).trans verdict end P455EffectiveChain end /- Begin Problem455MarkedPath (from finite-semigroup-identity-bases). -/ section namespace P455MarkedPath open P455Witness P455Paths P455ContactLift P455SourceFamilies P455SourceTheorem open P455CrossedSupport P455OriginalWalk P455Compression noncomputable 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 proposed walk in the source. All ordered comparisons and all witness labels in its query 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 y let v := ruleWord r allow mark u x y let d := donor v h r let 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) := by let names := retained r allow mark u x y let v := ruleWord r allow mark u x y let e := expand u names have exp : P455Retained.Expansion v e (fun a => a ∈ names) := canonical u names have orig : v.flatMap e = u := recover u names obtain ⟨hr,cx,cy,_⟩ := flip_counts capU flip have pos : 0 < r := by omega have 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 cross have guard := actual_guard pos capU hx hy side uniform have ks := (guard seed (near_self _ _)).1 have 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 ▸ capU have guard' : OriginalGuard r allow mark (v.flatMap e) (fun a => a ∈ names) seed 6 := orig.symm ▸ guard obtain ⟨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 walks exact ⟨seed,z,l,k,side,start,path,eq,vw,ev,cmp,walks⟩ end P455MarkedPath end /- Begin Problem455SupportBound (from finite-semigroup-identity-bases). -/ section namespace P455SupportBound open P455Witness P455Paths P455ContactGeometry P455CrossedSupport Problem455.Slots open P455FirstRewrite (names mem_names names_distinct size_le) noncomputable def occupants (u : W) (t i : Nat) : W := by classical exact (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 := by classical simp 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 ≤ K private 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 := by induction 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_self simp 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 overcount non-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 := by classical exact 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 := by classical by_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 := by classical rw [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 j private 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 := by cases j <;> exact List.mem_cons_self private 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 := by induction 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]; omega private 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 := by induction p generalizing t n j with | nil => exact seed_mem _ _ _ | cons e p ih => obtain ⟨a,c⟩ := e cases 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.1 have into := next_slot ball slot occ have 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 := by let F := next r allow mark u x y let D := 7*K let ball := explore F 6 x ++ explore F 6 y let covered := ball ++ ball.flatMap F have all (b) (hb : InBall r allow mark u x y b) : b ∈ ball := by have mem (s) (origin : s=x ∨ s=y) (near : Near r allow mark u s b 6) : b ∈ explore F 6 s := by obtain ⟨p,wp,eq,len⟩ := near exact eq ▸ walked s s origin 0 6 (by decide) (near_self s 0) p wp len exact 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 := by obtain ⟨_,needs⟩ := mem_retained.mp ((mem_names _ _).mp ha) unfold covered apply List.mem_append.mpr rcases 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 a have count := size_le (names_distinct _) included have size : ball.length ≤ 2*geometric D 6 := by have bx := explore_bound F D fb 6 x have by' := explore_bound F D fb 6 y dsimp only [ball]; rw [List.length_append]; omega have more := flat_bound ball F D (fun t _ => fb t) have gross : covered.length ≤ ball.length*(1+D) := by dsimp only [covered]; rw [List.length_append,Nat.mul_add,Nat.mul_one]; omega have lim := Nat.mul_le_mul_right (1+D) size have fin := Nat.le_trans count (Nat.le_trans gross lim) simpa only [D,Nat.mul_assoc,Nat.mul_left_comm,Nat.mul_comm] using fin theorem 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 consecutive indexed copies, whether or not the containing word is capped. -/ theorem owner_absent (u : W) (t i : Nat) : ¬ occupies u t i t := by intro occ obtain ⟨j,hj⟩ := occ have mem : (t,i+1) ∈ events u := hj.mem (by simp) have b := (P455SlotOrigin.event_bounds (fun _ => 0) u t (i+1) mem).2 obtain ⟨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 saturated occupants 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)) := by classical let xs := (occupants u t i).take 5 have 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 _).mpr intro q mem obtain ⟨a,ha,rfl⟩ := List.mem_map.mp mem have occ := inside a ha exact ⟨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 := by intro t ball i slot exact Nat.le_of_not_lt (fun h => by obtain ⟨xs,w⟩ := overflow_of_more uniform cmp ball slot h exact none t ball i slot xs w) /-- Uniform one-step rank under the actual source geometric guard and validity of 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 y M.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 6 P455FirstRewrite.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)) := by let u := P455Uncrossed.side f l k b let keep := retained r allow mark u x y have flip : ClosedFlip r allow u x y := ⟨f,b,l,k,hp,hq,valid,rfl⟩ obtain ⟨hr,cx,cy,_⟩ := flip_counts cap flip have 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 semantic have small : (names keep).length ≤ 2*(1+28)*geometric 28 6 := retained_bound_four capacity have scaled := Nat.mul_le_mul_left r small obtain ⟨U,V,L,R,h,hyp,nu,nv,ne,src,dst⟩ := step refine ⟨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 P455SupportBound end /- Begin Problem455StructuralProduct (from finite-semigroup-identity-bases). -/ section namespace P455StructuralProduct open P455Structural P455Witness P455Quotient P455Closure P455Uncrossed open P455SourceFamilies P455FirstTesters P455FirstRewrite def templates (r : Nat) := Problem455Finite.wordsUpTo (List.range 4) (4*r) structure Index (r : Nat) (allow : Tag → Prop) where pos : Fin (templates r).length cap : P455Closure.Cap r ((templates r).get pos) cmp : Compressed r ((templates r).get pos) test : Structural ((templates r).get pos) r allow def Index.T (i : Index r allow) := (templates r).get i.pos abbrev Carrier (r : Nat) (allow : Tag → Prop) := (i : Index r allow) → Q (plain r) i.T def product (r : Nat) (allow : Tag → Prop) : Model (Carrier r allow) where op := 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 := by induction w with | nil => rfl | cons x xs ih => exact congrArg (mul (plain r) i.cap (f x i)) ih theorem 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) := by intro val funext i rw [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 construction satisfy the structural subproduct identity for every retained-name list containing 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) := by obtain ⟨g,L,K,gp,gq,gv,eq,_⟩ := P455CompressedFrame.canonical_pair f l k names hx hy hp hq valid bit cap rw [eq,eq] exact identity g L K x y gp gq gv end P455StructuralProduct end /- Begin Problem455PaddedMatchings (from finite-semigroup-identity-bases). -/ section namespace P455PaddedMatchings open P455PaddedPorts P455PaddedTiles def 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 omega theorem id_inj {w y x z q : Nat} (hx : x omega theorem id_bound {w h y x : Nat} (hy : y simp at lt | succ => omega let y := i/w let j := i%w have jo : j [] | 1 => [.single (f start)] | n+2 => .pair (f start) (f (start+1)) :: pairs f (start+2) n def line (skip : Bool) (f : Nat → Nat) (size : Nat) := if skip then match size with | 0 => [] | k+1 => .single (f 0) :: pairs f 1 k else pairs f 0 size private theorem pair_cells (f : Nat→Nat) (s n : Nat) : (pairs f s n).flatMap cells = (List.range' s n).map f := by induction 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 := by cases 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 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 omega exact .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 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 p exact ⟨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) n private 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)) := by simp [lines,List.flatMap_assoc,line_cells] theorem lines_unique (m n : Nat) (skip : Bool) (f : Nat→Nat→Nat) (inj : ∀ z 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_mem intro z t hz ht ne a ha b hb eq obtain ⟨x,hx,rfl⟩ := List.mem_map.mp ha obtain ⟨j,hj,rfl⟩ := List.mem_map.mp hb exact ne (inj z (List.mem_range.mp hz) x (List.mem_range.mp hx) t (List.mem_range.mp ht) j (List.mem_range.mp hj) eq).1 def 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 ↔ i0 rfl | cons a xs ih => simp [cells,ih] theorem wrap_unique {t : Nat} (ht : 1 simp at m | cons x ks ih => obtain ⟨out,tail⟩ := List.nodup_cons.mp nd by_cases e : a=x · subst x; simp [List.count_cons,List.count_eq_zero.mpr out] · have z : a∈ks := by simpa [e] using m simp [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 := by induction bs with | nil => rfl | cons b bs ih => change ((cells b ++ cells b) ++ phase bs).count c=2*((cells b) ++ bs.flatMap cells).count c simp only [List.count_append,ih]; omega theorem count_role (s : W) (c a : Nat) (target : a=owner c ∨ a=mate c) : (s.flatMap roles).count a=s.count c := by induction s with | nil => rfl | cons k s ih => simp only [List.flatMap_cons,List.count_append,ih] by_cases eq : k=c · subst k rcases target with rfl|rfl <;> simp [roles,List.count_cons,owner,mate] <;> omega · have non : a∉roles k := by unfold roles simp only [List.mem_cons,List.not_mem_nil,or_false] unfold owner mate at target ⊢; omega simp [List.count_eq_zero.mpr non,List.count_cons,eq,Ne.symm eq] /-- Context can contribute arbitrarily many other events, including earlier or later copies of the four observed roles. Only the counts at the actual phase 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 := by let active (e : Event) := decide (e.1∈ks ∧ k≤e.2 ∧ e.20 let p : Nat → Nat := fun a=>pre.count a let q : Nat → Nat := fun a=>pre.count a+mid.count a have whole : events (pre++mid++post)=stamp zero pre ++ (stamp p mid ++ stamp q post) := by simp 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 rfl rw [e,f] have none₁ : (stamp zero pre).filter active=[] := by apply List.filter_eq_nil_iff.mpr rintro ⟨a,i⟩ mem yes obtain ⟨m,lo,_⟩ := of_decide_eq_true yes have lim := (P455ContactGeometry.stamp_range zero pre mem).2 change i<0+pre.count a at lim have := before a m; omega have none₂ : (stamp q post).filter active=[] := by apply List.filter_eq_nil_iff.mpr rintro ⟨a,i⟩ mem yes obtain ⟨m,_,hi⟩ := of_decide_eq_true yes have lim := (P455ContactGeometry.stamp_range q post mem).1 change pre.count a+mid.count a≤i at lim have := before a m; have := inside a m; omega have middle : (stamp p mid).filter active=stamp (fun _=>k) (select ks mid) := by rw [P455ContactGeometry.project_stamp ks mid (fun _=>k) p (fun a m => (before a m).symm)] apply List.filter_congr rintro ⟨a,i⟩ mem by_cases m : a∈ks · have lim := P455ContactGeometry.stamp_range p mid mem change pre.count a≤i ∧ ik) (select ks mid) := by simp 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) := by apply List.filter_eq_self.mpr rintro ⟨x,i⟩ m have mem := stamped_mem_label (fun _=>k) (ks++ks) _ m have mx : x∈ks := by simpa using mem have lim := P455ContactGeometry.stamp_range (fun _=>k) (ks++ks) m simp only [List.count_append,count_one nd mx] at lim exact decide_eq_true ⟨mx,lim.1,by omega⟩ constructor · intro seq have sub := seq.filter active change ((stamp (fun _=>k) (ks++ks)).filter active).Sublist ((events (pre++mid++post)).filter active) at sub rw [full,observed] at sub have words := sub.map Prod.fst simp only [labels_of_stamp] at words have perm : (select ks mid).Perm (ks++ks) := by apply List.perm_iff_count.mpr intro a by_cases m : a∈ks · unfold select rw [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 eq rw [←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 := by let ks := roles i ++ roles j have 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; omega have nod : ks.Nodup := by simp [ks,roles,dis.1,dis.2.1,dis.2.2.1,dis.2.2.2.1,dis.2.2.2.2.1,dis.2.2.2.2.2] have window (a) (used : a∈ks) : (letters bs).count a=2 := by have ea : (a=owner i ∨ a=mate i) ∨ (a=owner j ∨ a=mate j) := by simpa only [ks,roles,List.mem_append,List.mem_cons,List.not_mem_nil,or_false] using used rcases 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 := by rw [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])] rfl rw [← ev,indexed_window nod prefixCount window] exact literal_phase_exact nd i j ne /-- The original tester query, without any hypothesis that it holds. The static typed-record and early-disjoint requirements are displayed separately from 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 := by dsimp only have obs := indexed_port_exact (post:=post) ne nd mi mj prefixCount constructor · 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 m have lt := port.isLt simp only [List.mem_cons,List.not_mem_nil,or_false] at m rcases m with h|h|h|h|h|h|h|h <;> rw [h] <;> dsimp <;> omega end P455PaddedPorts end /- 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 P455WriterFrontier open P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine def 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 := by intro h; have v := congrArg Fin.val h; change a.val=g at v; exact (Nat.ne_of_lt a.isLt) v def eraseTag (blank : Fin g) (a : Fin (g+1)) : Fin g := if h : a.val z.val) e) · intro e; exact Fin.ext (congrArg (fun z : Fin (g+1) => z.val) e) · have ne : a≠ink M.marker := by intro eq; subst a; exact h M.marker.isLt simp [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 where marker := ink M.marker blank := fresh g blank_ne := Ne.symm (ink_ne_fresh _) start := M.start delta z a := (M.delta z (eraseTag M.blank a)).map tagIns keeps := by intro z a i e cases h : M.delta z (eraseTag M.blank a) with | none => simp [h] at e | some j => rw [h] at e change some (tagIns j)=some i at e have e := Option.some.inj e subst i; exact ink_inj.trans ((M.keeps _ _ _ h).trans (erase_marker M a)) leftSafe := by intro z i e simp only [erase_ink] at e cases h : M.delta z M.marker with | none => simp [h] at e | some j => rw [h] at e change some (tagIns j)=some i at e have e := Option.some.inj e subst i; exact M.leftSafe _ _ h def alphabet (M : Ordinary g q) (A : Alphabet M) : Alphabet (monitor M) where bit 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 g def 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 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=0 cases 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) := by suffices h : inputTape (monitor M) (alphabet M A) x=tape x.length (inputTape M A x) by change (⟨_,0,M.start⟩ : Config (g+1) q)=⟨_,0,M.start⟩ rw [h] rfl funext j cases j with | zero => simp [inputTape,tape,monitor] | succ i => by_cases h : i simp [dest] <;> omega · intro j lt have ne : j≠c.pos := by omega simp [writeAt,ne,h.2.1 j (by omega)] · intro j by_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) := by have k : writeAt (tape n c.tape) c.pos (ink i.symbol)= tape (max n c.pos) (writeAt c.tape c.pos i.symbol) := by funext j by_cases eq : j=c.pos · subst j; simp [tape,writeAt,Nat.le_max_right] · have pos := h.1 have iff : j≤max n c.pos ↔ j≤n := by omega simp [writeAt,tape,eq,iff] have s := ins_eq M h rw [e] at s change instruction (monitor M) (liftCfg n c)=some (tagIns i) at s rw [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) := by induction t with | zero => exact ⟨_,input_good M A x,input_eq M A x⟩ | succ t ih => obtain ⟨n,ok,sim⟩ := ih let c := follow M (inputConfig M A x) t change ∃ 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 ok change instruction (monitor M) (liftCfg n c)=(instruction M c).map tagIns at stop rw [e] at stop exact ⟨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 P455WriterFrontier end /- Begin Problem455EffectiveMachineRelabel (from finite-semigroup-identity-bases). -/ section namespace P455EffectiveRelabel open P455MachineLocal P455MachineCleanup P455MachineTable P455EffectiveMachine open P455EffectiveChain structure Emb (g h : Nat) where enc : Fin g → Fin h back : Fin h → Fin g undo : ∀ a, back (enc a)=a theorem Emb.inj (e : Emb g h) (a b) : e.enc a=e.enc b ↔ a=b := by constructor · 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 where marker := e.enc M.marker blank := e.enc M.blank blank_ne := fun equ => M.blank_ne ((e.inj ..).mp equ) start := M.start delta s x := if x=e.enc (e.back x) then (M.delta s (e.back x)).map (mapped e) else none keeps := by intro s x i yes split at yes next 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 yes change e.enc z.symbol=e.enc M.marker ↔ x=e.enc M.marker exact (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 => contradiction leftSafe := by intro s i yes simp only [e.undo,if_true] at yes cases st : M.delta s M.marker with | none => simp [st] at yes | some z => rw [st] at yes; obtain rfl := Option.some.inj yes exact M.leftSafe _ _ st def alpha (M : Ordinary g q) (A : Alphabet M) (e : Emb g h) : Alphabet (expand M e) where bit 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) := by cases 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) := by simp [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) := by unfold 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) := by funext 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) tape theorem 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) := by induction 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 := by obtain ⟨t,stop,ok⟩ := out refine ⟨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 chosen offset. 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.val def 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 true else if h : y-base (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 := by unfold number split next eq => simp [denumber,eq] next => split next eq => simp [denumber,eq] next => split next eq => simp [denumber,eq] next => split next eq => simp [denumber,eq] next => have zero : base+a.val≠0 := by omega have one : base+a.val≠1 := by omega have two : base+a.val≠2 := by omega have three : base+a.val≠3 := by omega simp [denumber,zero,one,two,three,Nat.add_sub_cancel_left,a.isLt] <;> omega def 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 := by simp [number] @[simp] theorem blank_number (M : Ordinary g q) (A : Alphabet M) (base) : number M A base M.blank=1 := by simp [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 := by cases b <;> simp [number,A.away,A.ink,Ne.symm A.distinct] end P455EffectiveRelabel end /- Begin Problem455SlotProduct (from finite-semigroup-identity-bases). -/ section namespace P455SlotProduct open P455Witness P455Paths P455SourceFamilies P455CrossedSupport Problem455.Slots def alphabet := List.range 9 def templates (r : Nat) := Problem455Finite.wordsUpTo alphabet (9*r) def pairMark (a b : Nat) : Marking := fun x y => x = a ∧ y = b structure Index (r : Nat) (allow : Tag → Prop) where num : Fin (templates r).length a : Fin 9 b : Fin 9 cap : 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.num def 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.T def evalP (v : Nat → Carrier r allow) (w : W) : Carrier r allow := fun i => P455Quotient.eval i.R i.cap (fun x => v x i) w def Identity (r : Nat) (allow : Tag → Prop) (u w : W) := ∀ v : Nat → Carrier r allow, evalP v u = evalP v w theorem 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; rfl theorem 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 := by induction 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 ⊢; omega theorem capped_length {r : Nat} (k : Nat) (w : W) (cap : P455Closure.Cap r w) (names : ∀ x ∈ w, x < k) : w.length ≤ k*r := by induction 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 => by obtain ⟨mem,p⟩ := List.mem_filter.mp hx have h := names x mem have e : x ≠ k := by simpa [bne_iff_ne] using p omega) have ct := cap k have tot := remove_count w k rw [Nat.succ_mul]; omega def 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 := by induction 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 at the coordinatewise erasing-and-renaming valuation, even if other coordinates 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) := by let v : Nat → Carrier r allow := fun x j => P455Quotient.ofWord j.R j.T (image keep x) have comp := congrFun (valid v) i change P455Quotient.eval i.R i.cap _ u = P455Quotient.eval i.R i.cap _ w at comp rw [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 comp have 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).2 rw [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 rfl intro z z' mv old exact 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) := by induction 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 := by cases 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) := by obtain ⟨_,_,_,ne⟩ := flip_counts cap flip obtain ⟨f,b,l,k,hp,hq,ok,rfl⟩ := flip refine ⟨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 h end P455SlotProduct end /- Begin Problem455PaddedSnake (from finite-semigroup-identity-bases). -/ section namespace P455PaddedMatchings open P455PaddedTiles def rowEnd (w y x : Nat) : Prop := if odd y then x=0 else x+1=w def 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 := by by_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 simp [rowEnd,par] at endRow <;> simp [idAt,par,Nat.mul_add] <;> omega theorem down_id {w y x : Nat} (hx : x simp [rowEnd,par] at endRow <;> simp [idAt,odd_succ,par] <;> omega theorem stepping {w h i : Nat} (bound : i+1 simp [rowEnd,par] at b refine ⟨y,hy,x+1,by omega,eq,?_,.inl ⟨par,rfl,rfl⟩⟩ simp [idAt,par] at eq ⊢; omega | true => simp [rowEnd,par] at b refine ⟨y,hy,x-1,by omega,eq,?_,.inr (.inl ⟨par,rfl,by omega⟩)⟩ simp [idAt,par] at eq ⊢; omega theorem last_cell {w h : Nat} (pos : 0 simp at pos | succ => omega have hy : 0 simp at pos | succ => omega let y := h-1 let x := if odd y then 0 else w-1 have hx : x omega have b : rowEnd w y x := by cases p : odd y <;> simp [rowEnd,x,p] <;> omega have e : y+1=h := by dsimp [y]; omega have z := end_id hx b rw [e] at z exact ⟨y,by dsimp [y]; omega,x,hx,e,b,by omega⟩ def decodeRow (w i : Nat) := i/w def decodeCol (w i : Nat) := if odd (decodeRow w i) then w-1-(i%w) else i%w theorem decode_id {w y x : Nat} (hx : x omega have yr : decodeRow w (idAt w y x)=y := by simp [decodeRow,idAt,Nat.mul_add_div wt,Nat.div_eq_of_lt off] refine ⟨yr,?_⟩ unfold decodeCol rw [yr] simp only [idAt,Nat.mul_add_mod,Nat.mod_eq_of_lt off] cases p : odd y <;> simp <;> omega def 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 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+10) l e).2 omega have nt : (a,k+1) ∉ stamp (fun x=>l.count x+m.count x) t := by intro e; have := (P455ContactGeometry.stamp_range (fun x=>l.count x+m.count x) t e).1 omega have rest := trim _ _ _ _ nl sub have back := rest.reverse simp only [List.reverse_append,List.reverse_cons,List.reverse_nil,List.nil_append, List.cons_append,List.singleton_append] at back have small := (trim _ _ _ _ (by simpa using nt : (a,k+1) ∉ (stamp (fun x=>l.count x+m.count x) t).reverse) back).reverse have mid : [(a,k),(z,j),(a,k+1)].Sublist ((events m).map (shift (fun x=>l.count x))) := by simpa using small obtain ⟨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 ev change e.1=z at lab rw [←lab]; exact stamped_mem_label (fun _=>0) m e em theorem 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 := by refine ⟨roles c,by simp [roles],?_⟩ intro z occ have ne : owner c≠mate c := by simp [owner,mate] have count : (privateCell c).count a=3 := by rcases (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) occ simpa [privateCell,roles,or_assoc,or_left_comm,or_comm] using mem private 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 := by simp [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 := by simp only [roles,List.mem_cons,List.not_mem_nil,or_false] at m same unfold owner mate at m same; omega private theorem index_mem (bs : List Block) (a c : Nat) (role : a∈roles c) (m : a∈letters bs) : c∈bs.flatMap cells := by obtain ⟨x,hx,mx⟩ := List.mem_flatMap.mp m have eq := role_from _ _ _ role mx rw [eq] obtain ⟨b,hb,inBlock⟩ := List.mem_flatMap.mp hx exact 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 := by obtain ⟨b,inBs,inBlock⟩ := List.mem_flatMap.mp present obtain ⟨pre,post,e⟩ := List.append_of_mem inBs subst bs simp only [List.flatMap_append,List.flatMap_cons] at nd have ds := (List.pairwise_append.mp nd).2.2 have noPre : a∉letters pre := by intro hm exact ds c (index_mem pre a c role hm) c (List.mem_append_left _ inBlock) rfl let names := (cells b).flatMap roles have 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 has have cut : l++letters (pre++b::post)++t=(l++letters pre)++(names++names)++(letters post++t) := by rw [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 occ rw [cut] at occ have 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) occ simpa using hit end P455PaddedPorts end /- Begin Problem455WriterSweep (from finite-semigroup-identity-bases). -/ section namespace P455WriterSweep open P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine open P455EffectiveChain P455WriterFrontier def reach (M : Ordinary g q) (c d : Config g q) := ∃ t, follow M c t=d theorem trans {M : Ordinary g q} {a b c} (h : reach M a b) (k : reach M b c) : reach M a c := by obtain ⟨u,rfl⟩ := h; obtain ⟨v,hv⟩ := k exact ⟨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 else if 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 := by have 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 then if a=ink M.marker then some ⟨1,a,.right⟩ else some ⟨0,a,.left⟩ else if s=1 then if 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 where marker := ink M.marker blank := fresh g blank_ne := Ne.symm (ink_ne_fresh _) start := 0 delta := control M O read keeps := by intro s a i e unfold control at e split 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; rfl leftSafe := by intro s i e simp only [control,if_pos rfl,ink_ne_fresh,↓reduceIte] at e split at e · cases e; exact Direction.noConfusion · split at e · cases e; exact Direction.noConfusion · contradiction def mix (src dst : Nat→Fin k) (p i : Nat) := if i

exact ⟨0,rfl⟩ | succ p ih => apply trans _ ih apply single have 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 have e : p=n+1 := by omega subst p have ne := Ne.symm (ink_ne_fresh M.marker) have whole : mix src dst (n+1)=dst := by funext i; by_cases le : i have le : p≤n := by omega apply trans _ (ih (p+1) (by omega)) apply single have 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⟩ := by simp [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 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 := by let 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 rfl have start : mix src dst 1=src := by funext 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⟩ := by rw [start]; apply single have i : instruction (sweep M O read) ⟨src,0,0⟩=some ⟨1,src 0,.right⟩ := by simp [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)=none simp [control,(mp 0).mpr rfl] end P455WriterSweep end /- 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 P455RelabeledChain open P455MachineLocal P455MachineCleanup P455MachineTable P455EffectiveMachine open P455EffectiveChain P455EffectiveRelabel def 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 := by apply Fin.ext exact (mark_number W O 4).trans (mark_number D B (4+g)).symm theorem 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 := by funext j; rw [input_tape]; apply Fin.ext cases 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).symm def 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 := by obtain ⟨t,stopped,pos,tape⟩ := writing refine ⟨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 two different bit alphabets for input and output. The reader's original alphabet and final-state convention are unrestricted. The fresh common alphabet 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 P455RelabeledChain end /- Begin Problem455SlotSaturation (from finite-semigroup-identity-bases). -/ section namespace P455SlotSaturation open P455Witness P455Paths P455ContactLift P455OriginalWalk P455CrossedSupport open P455SlotProduct P455SourceFamilies P455SourceTheorem P455MarkedPath open P455DefectRename Problem455.Slots theorem 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 := by obtain ⟨tag,bit,marked⟩ := flip_anchor cap flip let n : Node := ⟨x,y,tag⟩ intro t near i slot bad occ apply Classical.byContradiction intro ne have defic : u.count bad < r := by have := cap bad; omega have route : ∃ side : Bool, Near r allow mark u (if side then n.mate else n.owner) t 6 := by rcases near with hx | hy · exact ⟨false,hx⟩ · exact ⟨true,hy⟩ obtain ⟨side,rt⟩ := route obtain ⟨keep,s,len,ho,hm,sx,sy,_,kind,labels,capT,test⟩ := canonical_defect cap n bit side t i bad marked rt slot occ defic let T := (select keep u).map keep.idxOf have 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 mem let 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 := sx have yb : s.anchor.mate = b.val := sy have fm : markNode s.anchor = pairMark a b := by unfold markNode pairMark rw [xa,yb] have tc : Holds r allow (pairMark a b) T (s.query r) := fm ▸ test let 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.symm change select [keep.idxOf x, keep.idxOf y] _ = select [keep.idxOf x, keep.idxOf y] _ at proj rw [← binary_select_map keep u ho hm, ← binary_select_map keep w ho hm] at proj have kept' (word : W) (c : Nat) (hc : c ∈ select [x,y] word) : c ∈ keep := by rcases (by simpa using kept hc : c = x ∨ c = y) with h|h · exact h ▸ ho · exact h ▸ hm have decoded := congrArg (List.map (decode keep)) proj dsimp only [n] at decoded exact changed (by simpa only [decode_map (kept' u),decode_map (kept' w)] using decoded) abbrev noMark : Marking := fun _ _ => False theorem 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 := by have w0 : Walk r allow noMark v t p := remark_walk t p w apply remark_walk (mark := noMark) t p clear w induction 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 := by apply path.transport uf intro w z mv old t near i slot b occ have pull {s} (h : Near r allow mark z s t 6) : Near r allow mark w s t 6 := by obtain ⟨p,wa,ep,len⟩ := h exact ⟨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 y let v := ruleWord r allow mark u x y let d := donor v h r let 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 cross end P455SlotSaturation end /- Begin Problem455EdgeProduct (from finite-semigroup-identity-bases). -/ section namespace P455EdgeProduct open P455Witness P455Paths P455EdgeSource P455EdgeProjection P455PortReflection P455CertificateReach open P455DefectRename P455SlotProduct Problem455.Slots open P455FirstRewrite (Model) abbrev W := List Nat def 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) where num : Fin (words r).length a : Fin 14 b : Fin 14 c : Fin 14 d : Fin 14 cap : 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.num def 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.T def product (r : Nat) (allow : Tag → Prop) (ts : Tiles) : Model (Carrier r allow ts) where op := 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) := by let 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) := by induction z with | nil => rfl | cons a z ih => change P455Quotient.mul i.R i.cap (val a i) _ = _ rw [ih]; rfl exact (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 := by cases 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 test forces both marked binary projections to agree with the opposite word. 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 := by let keep := names ts e let T := template ts e u let f := keep.idxOf obtain ⟨ct,namesT,cert⟩ := canonical_edge cap ts e ok have hr : 0 < r := by have h : e.a.tag.length + 16 = r := ok.1.2.1; omega have exactT (x : Nat) : x ∈ T ↔ x ∈ names ts (sendEdge f e) := by rw [names_send] constructor · intro h; obtain ⟨z,hz,rfl⟩ := List.mem_map.mp h exact List.mem_map_of_mem (kept hz) · intro h; obtain ⟨z,hz,rfl⟩ := List.mem_map.mp h apply List.mem_map_of_mem apply List.count_pos_iff.mp change 0 < (select keep u).count z rw [P455DefectProjection.select_count keep u z hz,saturated cap ts e ok hz] exact hr have 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).1 obtain ⟨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 comp have sameT : T = i.T := eq.symm change P455Quotient.ofWord i.R i.T T = _ at comp rw [sameT] at comp have good : P455Quotient.Good i.R i.T i.T := ⟨_,.refl _,[],[],by simp⟩ have path := ((P455Quotient.same_nonzero_class i.R good).mp comp).2 have 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 := by have 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 pr change select [keep.idxOf x,keep.idxOf y] ((select keep u).map keep.idxOf) = _ at pr rw [← binary_select_map keep u hx hy,← binary_select_map keep w hx hy] at pr have k (z : W) (j : Nat) (mem : j ∈ select [x,y] z) : j ∈ keep := by rcases (by simpa using kept mem : j=x ∨ j=y) with rfl|rfl <;> assumption simpa only [decode_map (k u),decode_map (k w)] using congrArg (List.map (decode keep)) pr exact ⟨recover _ _ ao am (.inl ⟨rfl,rfl⟩),recover _ _ bo bm (.inr ⟨rfl,rfl⟩)⟩ end P455EdgeProduct end /- Begin Problem455PaddedWord (from finite-semigroup-identity-bases). -/ section namespace P455PaddedWord open P455PaddedPorts P455PaddedMatchings P455RectangleRank abbrev W := List Nat def 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 roles def middle (h w k : Nat) (tag : Nat → List Bool) : W := portChunks h w 5 ++ suffix h w k tag def tail (t : Nat) : W := (List.range t).flatMap (mutableCell (constant false)) theorem matching_unique {h w : Nat} (size : 1 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 size theorem matching_cells {h w : Nat} (size : 1 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 i theorem columns_eq (h w : Nat) : columnCells h w=(horizontal h w false).flatMap cells := by change _ = (lines h w false (idAt w)).flatMap cells simp [columnCells,lines,List.flatMap_assoc,line_cells] theorem columns_unique (h w : Nat) : (columnCells h w).Nodup := by rw [columns_eq]; exact horizontal_unique .. theorem columns_cells (h w i : Nat) : i∈columnCells h w ↔ i decide (Needed r allow mark u x y b)) = (fun b => decide (Needed r allow mark v x y b)) := by funext 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 := by induction h with | nil => rfl | cons _ _ ih => simp [ih] | swap => simp [List.sum_cons]; omega | trans _ _ ih jh => exact ih.trans jh theorem pieces_perm (w : W) {s t : W} (perm : s.Perm t) : pieces s w = pieces t w := by induction 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 := by simp 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 := by classical have near (a b : Nat) (m m' : Marking) (h : Near r allow m u a b 6) : Near r allow m' u a b 6 := by obtain ⟨p,w,ep,len⟩ := h exact ⟨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 := by rcases h with h|⟨t,i,h,hi,occ⟩ · exact .inl (ball _ _ _ h) · exact .inr ⟨t,i,ball _ _ _ h,hi,occ⟩ unfold retained apply List.filter_congr intro b _ simp [show Needed r allow mark u x y b ↔ Needed r allow mark' u x y b from ⟨need _ _ _,need _ _ _⟩] end P455RetainedVariant end /- Begin Problem455ProfileComponent (from finite-semigroup-identity-bases). -/ section namespace P455ProfileComponent open P455Witness P455Closure P455SlotProduct P455SlotSaturation Problem455.Slots abbrev W := List Nat theorem profile_support (a b : Nat) (tag : Tag) (bit : Bool) {z : Nat} (m : z ∈ profile a b tag bit) : z = a ∨ z = b := by rw [← profile_eq] at m obtain ⟨c,_,rfl⟩ := List.mem_map.mp m cases c <;> simp theorem profile_length (a b : Nat) (tag : Tag) (bit : Bool) : (profile a b tag bit).length = 2 * (tag.length + 16) := by cases bit <;> simp [profile,pair,profile_prefix_length] <;> omega theorem profile_cap {a b : Nat} (ne : a ≠ b) (tag : Tag) (bit : Bool) : Cap (tag.length + 16) (profile a b tag bit) := by intro x have tagct (x : Nat) : (tag.flatMap (pair a b)).count x ≤ tag.length := by induction 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 * <;> omega have cp := tagct x cases 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 * <;> omega def 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 := by have 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) := by induction 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)) := by let f := frame a b tag have cp : Cap r (profile a b tag bit) := length ▸ profile_cap ne tag bit have cf : Cap r ([] ++ f.core bit ++ []) := by simpa [f,frame_core] using cp refine ⟨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 := by constructor · intro path have supp (x : Nat) (inU : x ∈ u) : x=a ∨ x=b := by have ct := P455Quotient.count_walk (rules r allow noMark) path x exact 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 supp have selfT : select [a,b] (profile a b tag bit) = profile a b tag bit := by apply List.filter_eq_self.mpr intro x h; simpa using profile_support a b tag bit h have 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) := by constructor · 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 := by obtain ⟨f,t,l,k,ok,rfl,_,cp⟩ := h have 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 small have eq := ok.1 omega theorem 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 := by constructor · intro eq have path := ((P455Quotient.same_nonzero_class _ live).mp eq).2 exact path.transport (P := fun z => u=z) rfl (fun mv e => by subst_vars; have := move_size mv; omega) · rintro rfl; rfl theorem 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 noMark let T := profile a b tag bit P455Quotient.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))) := by let R := rules r allow noMark let T := profile a b tag bit change P455Quotient.ofWord R T u = P455Quotient.ofWord R T v ↔ _ constructor · intro eq by_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 valid have lens := congrArg List.length e simp only [profile_length,length,List.length_append] at lens have 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.symm have path := ((P455Quotient.same_nonzero_class _ valid).mp eq).2 rw [full] at path exact .inr (.inl ⟨⟨i,full⟩,(variants ne length allowed i v).mp path⟩) · have dead : ¬ P455Quotient.Good R T v := by intro 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 P455ProfileComponent end /- Begin Problem455GridRows (from finite-semigroup-identity-bases). -/ section namespace P455GridRows open P455Witness P455Paths Problem455.Slots /-- Horizontal and vertical compatible tile pairs obey the flags in the machine construction. The bare `Tiles` structure does not impose them. -/ structure Laws (ts : Tiles) : Prop where horiz : ∀ 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 a vert : ∀ 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 a def 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=c private 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-hand upper 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) := by have lawH := law.horiz _ _ edge.1 have nr := lawH.1 have ny : ts.bottom y.a.tag=false := lawH.2.2.2.1.symm.trans nb have square : Holds r allow mark w (downward ts x.right x.diagonal) ∧ Holds r allow mark w (rightward ts x.down x.diagonal) := by simpa [flagQ,nr,nb,Holds] using hX.2.2.2.2.1 have toY := fx .right x.right y.a (active hX.1 nr) edge have downY := active hY.2.2.1 ny have d : x.diagonal = y.down := fy .down _ _ (toY ▸ square.1) downY exact ⟨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 := by have suc := arr.2.2.2 simp only [chosenSuccessor,endRow,notBottom,Bool.and_false,Bool.false_eq_true,if_false,if_true] at suc exact suc.1.symm private 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) := by have endRow : endOfRow ts e.a = false := by simp [endOfRow,odd,right] have suc := arr.2.2.2 simp only [chosenSuccessor,endRow,Bool.false_and,Bool.false_eq_true,if_false,odd] at suc exact suc.1 ▸ active arr.2.2.1.1 right private 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) := by have endRow : endOfRow ts e.a = false := by simp [endOfRow,odd,left] have suc := arr.2.2.2 simp only [chosenSuccessor,endRow,Bool.false_and,Bool.false_eq_true,if_false,odd,if_true] at suc exact suc.1 ▸ active arr.2.2.1.2.1 left /-- An arbitrary candidate row is forced onto the cycle once its first cell is known to lie there. Induction obtains functionality from the trace before 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 intro _; exact init | succ j ih => intro le have 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) := by cases odd with | false => have R : Holds r allow mark w (rightward ts (atCell (start+j)).a (row (j+1))) := here ▸ one have next := goes_right _ (arrow (start+j)) p (law.horiz _ _ R.1).1 exact functional _ .right _ _ next R | true => have L : Holds r allow mark w (rightward ts (row (j+1)) (atCell (start+j)).a) := here ▸ one have next := goes_left _ (arrow (start+j)) p (law.horiz _ _ L.1).2.1 exact functional _ .left _ _ next L exact (continuous _).symm.trans eq /-- Positive left-to-right ordering of a nonbottom upper row; its cells are given by positions in the trace. This yields the entire lower right chain and 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 active (arrow (index j)).2.2.1.2.2.1 (nonbottom _ hj),?_⟩ intro j hj exact (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 strict numerical 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 := by induction ls with | nil => cases sub | cons x ls ih => obtain ⟨fresh,distinct⟩ := List.nodup_cons.mp nd cases 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_self have 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.tag theorem 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 := by have h := arr.2.2.2 change (endOfRow ts e.a && ts.bottom e.a.tag)=false at forward simp only [chosenSuccessor,forward,Bool.false_eq_true,if_false] at h exact idx_lt _ _ _ (stamp_unique _ _) h.2.2 /-- On an indefinitely continued trace of genuine arrows (in particular a repeated 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 := by apply Classical.byContradiction intro none have forward (j) : Return ts (atCell (start+j))=false := by cases e : Return ts (atCell (start+j)) with | false => rfl | true => exact (none ⟨j,e⟩).elim have grows (j) : j ≤ position w (atCell (start+j)).a := by induction j with | zero => exact Nat.zero_le _ | succ j ih => have inc := forward_increases _ (arrow _) (forward j) rw [continuous] at inc exact Nat.lt_of_le_of_lt ih inc have impossible := grows ((events w).length+1) have bound (z : Event) : (events w).idxOf z ≤ (events w).length := by by_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 impossible omega theorem 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 := by have h := arr.2.2.2 change (endOfRow ts e.a && ts.bottom e.a.tag)=true at back simp only [chosenSuccessor,back,if_true] at h simpa [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, and identify each prospective cell in the lower row with its actual trace index. 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 simp [last,column] have ending : endOfRow ts (atCell (index last)).a=true := by rw [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 nonbottom have 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 := by have 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 exact h j le | false => have u := h (n-(j+1)) (by omega) have ix : n-(j+1)+1=n-j := by omega simpa only [row,column,Bool.not_false,if_true,ix] using u have trace := trace_row law atCell arrow continuous functional row n start (!odd) init rowOdd adjacent dsimp only intro j le have 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] <;> omega simpa only [row,twice,start,last] using trace (column n (!odd) j) c end P455GridRows end /- Begin Problem455CatalogueBounds (from finite-semigroup-identity-bases). -/ section /- Exact finite witness search for the two-mark catalogue. Syntactically unused fields are unbounded in the Lean index. Every successful witness has a representative using only occurring names and admitted tags, even when nodes and labels alias. -/ namespace P455CatalogueBounds open P455Witness P455Paths P455CertificateReach P455EdgeProjection Problem455.Slots abbrev W := List Nat def 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 := by cases 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 := by cases 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 := by simp only [fields,canonical,List.mem_cons,List.not_mem_nil,or_false] at h rcases 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 dd all_goals exact .anchor def 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 := by obtain ⟨_,_,yes,bit,pr⟩ := valid have mem (z : Nat) (side : z=node.owner ∨ z=node.mate) : z∈w := by have m : z ∈ select [node.owner,node.mate] w := by rw [pr]; rcases side with rfl|rfl <;> simp [profile,profilePrefix] exact (List.mem_filter.mp m).1 exact 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 are kept. 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 := by exact ⟨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 for duplicate-free finite alphabets, including all five alphabets used by the concrete model. Distinct isomorphic templates remain separate. -/ theorem words_nodup {α : Type} (alphabet : List α) (nd : alphabet.Nodup) (bound : Nat) : (Problem455Finite.wordsUpTo alphabet bound).Nodup := by induction bound with | zero => simp [Problem455Finite.wordsUpTo] | succ n ih => apply List.nodup_cons.mpr constructor · simp [List.mem_flatMap] · apply List.pairwise_flatMap.mpr constructor · intro a _ exact ih.map (fun _ _ eq => (List.cons.inj eq).2) · apply nd.imp intro a b ab x hx y hy same obtain ⟨u,_,rfl⟩ := List.mem_map.mp hx obtain ⟨v,_,rfl⟩ := List.mem_map.mp hy exact ab (List.cons.inj same).1 theorem 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 := by exact ⟨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 P455CatalogueBounds end /- Begin Problem455PaddedCounts (from finite-semigroup-identity-bases). -/ section namespace P455PaddedWord open P455PaddedMatchings P455PaddedPorts P455RectangleRank Problem455.Slots private theorem cell_role {i a : Nat} (h : a∈roles i) : a=owner i ∨ a=mate i := by simpa [roles] using h theorem absent_other {i j a : Nat} (r : a∈roles i) (different : i≠j) : a∉roles j := by intro m; have p := cell_role r; have q := cell_role m; unfold owner mate at p q; omega private theorem range_count (i t : Nat) : (List.range t).count i=(if ih (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 := by induction 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 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 no simp [List.count_eq_zero.mpr no',e] rw [weighted _ _ _ _ _ ct,range_count]; split <;> simp theorem mutable_counts (i a : Nat) (role : a∈roles i) (bits : Nat→Bool) (t : Nat) : ((List.range t).flatMap (mutableCell bits)).count a=if i 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 no simp [List.count_eq_zero.mpr no',e] rw [weighted _ _ _ _ _ ct,range_count,Nat.one_mul] theorem port_count {h w : Nat} (size : 1 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 := by induction 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 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 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 ct j), List.length_range,count_role _ i a (cell_role role)] by_cases e : i e ((columns_cells h w i).mp m))] theorem word_count {h w k : Nat} (size : 1 omega theorem capped {h w k : Nat} (size : 1 omega end P455PaddedWord end /- Begin Problem455SingletonEvaluation (from finite-semigroup-identity-bases). -/ section namespace P455SingletonEvaluation open P455Witness P455ContactLift P455CrossedSupport P455SourceFamilies P455SourceTheorem open P455MarkedPath P455SlotSaturation P455SlotProduct P455RetainedVariant P455Compression open P455Uncrossed P455PortReflection P455EdgeSource Problem455.Slots abbrev W := List Nat def 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 b theorem designated_marks (c : Certificate) : MarksOnly (sourceMarks id c) c := by intro a b hit cases 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 := by obtain ⟨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) := by cases c <;> cases s <;> rfl theorem reindexed_marks (c : Certificate) (d : Nat → Nat) : sourceMarks id (transferred d c) = sourceMarks d c := by cases c <;> rfl theorem 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 := by let u := side f l k let R := rules r allow mark let names := retained r allow noMark (u false) x y have 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_right have 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 omega have 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 capF have perm (b : Bool) : names.Perm (retained r allow noMark (u b) x y) := by cases b · exact List.Perm.refl _ · exact same_retained mv x y have 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 := by unfold ruleWord; rw [retained_remark (mark' := noMark)]; exact eq0 b have neq : P455Quotient.eval R capT val (side g L K false) ≠ P455Quotient.eval R capT val (side g L K true) := by rw [← eq0,← eq0]; exact diff obtain ⟨b,live,⟨h,represent⟩,_⟩ := difference_live_representatives capT g L K val neq have reps := fun a ha => (represent a ha).2 have nd : P455Quotient.eval R capT val (side g L K b) ≠ P455Quotient.eval R capT val (side g L K (!b)) := by cases b · exact neq · exact Ne.symm neq obtain ⟨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 y have repv : ∀ a ∈ v, P455Quotient.ofWord R T (h a) = val a := by rw [show v = _ from eqm b]; exact reps have livev : P455Quotient.eval R capT val v ≠ P455Quotient.zero R T := by rw [show v = _ from eqm b]; exact live have pb : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ (u b) := by cases b; exact path; exact .snoc path mv have cb : Compressed r (u b) := by cases b · exact cmp · intro a z link exact 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 cs let names' := retained r allow mark (u b) x y obtain ⟨_,ax,ay,_⟩ := flip_counts (cbit b) (fc b) have eqNames : names.Perm names' := by change names.Perm (retained r allow mark (u b) x y) rw [retained_remark (mark' := noMark)]; exact perm b have xcnt : v.count x = r := (counts_retained _ _ _ (eqNames.mem_iff.mp hx)).trans ax have ycnt : v.count y = r := (counts_retained _ _ _ (eqNames.mem_iff.mp hy)).trans ay have ev := P455Quotient.eval_rep R capT val v h repv have good := (P455Quotient.nonzero_iff R).mp (ev ▸ livev) have cap := P455Quotient.good_cap R capT good let d := donor v h r refine ⟨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 cb theorem 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 diff end P455SingletonEvaluation end /- Begin Problem455GridAssembly (from finite-semigroup-identity-bases). -/ section namespace P455GridAssembly open P455GridRows P455Witness Problem455.Slots abbrev W := List Nat structure Rectangle (allow : Tag → Prop) (ts : Tiles) where height : Nat width : Nat tile : Nat → Nat → Tag allowed : ∀ 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 where parity : ∀ j, j≤n → ts.oddRow (c (s+column n odd j)).a.tag=odd left : ts.left (c (s+column n odd 0)).a.tag=true right : ts.right (c (s+column n odd n)).a.tag=true links : ∀ j, j by_cases e : ∃ k, k < j ∧ p k · obtain ⟨k,lt,ok⟩ := e exact 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) := by have ending : endOfRow ts (c i).a=false := by simp [endOfRow,p,q] have hs := (arr i).2.2.2 simp only [chosenSuccessor,ending,Bool.false_and,Bool.false_eq_true,if_false,p] at hs have h := (arr i).2.2.1.1 simp only [q,Bool.not_false,flagQ,if_true] at h rw [← cont, ← hs.1] exact h private 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 := by obtain ⟨j,ret⟩ := later_return c arr cont s have parity (a) (before : ∀ k, k 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 := by have n := before a (by omega) cases b : ts.right (c (s+a)).a.tag <;> simp_all have step := right_step c arr cont (s+a) p q exact (law.horiz _ _ step.1).2.2.2.2.1.symm.trans p have hasRight : ∃ a, ts.right (c (s+a)).a.tag=true := by apply Classical.byContradiction; intro missing have 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 := by cases b : ts.right (c (s+j)).a.tag <;> simp_all simp [Return,endOfRow,p,q] at ret obtain ⟨a,ha⟩ := hasRight obtain ⟨n,last,prior⟩ := min_bounded (fun i => ts.right (c (s+i)).a.tag=true) a ha refine ⟨n,?_,?_,?_,?_⟩ · intro k le; exact parity k (fun b lt => prior b (by omega)) · simpa [column] using left · exact last · intro k lt have p := parity k (fun b lb => prior b (by omega)) have q : ts.right (c (s+k)).a.tag=false := by have off := prior k lt cases b : ts.right (c (s+k)).a.tag <;> simp_all exact right_step c arr cont (s+k) p q private theorem row_const (n : Nat) (f : Nat → Bool) (step : ∀ j, j 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) := by let ix (j : Nat) := s+column n odd j have tr := advance_row law c arr cont funct ix n odd row.links nonbottom row.parity row.left row.right have en : ix (column n (!odd) 0)=s+n := by cases odd <;> simp [ix,column] simp only [en] at tr obtain ⟨vs,hs⟩ := lower_row law c arr funct ix n row.links nonbottom have 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) := by rw [tr j le]; exact vs j le refine ⟨⟨?_,?_,?_,?_⟩,down⟩ · intro j le exact (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 this first 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) where h : Nat t : Nat → Nat → Tag head : ∀ j, j≤n → t 0 j=first j ok : ∀ i j, i≤h → j≤n → allow (t i j) horizontal : ∀ i j, i≤h → j (c (s+column n odd j)).a.tag)) := by induction fuel using Nat.strongRecOn with | ind fuel ih => intro s n odd bound time row let tag (j : Nat) := (c (s+column n odd j)).a.tag have ok (j : Nat) : allow (tag j) := (arr _).1.2.2.1 have H (j) (lt : j 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 := by by_cases eq : j=n · subst j; simp [tag,row.right] · have lt : 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 jl have bi := (B j jl).trans bot simp [bi,Nat.le_zero.mp il] | false => have nonbottom (j : Nat) (le : j≤n) : ts.bottom (tag j)=false := (B j le).trans bot have nextLe : s+n+1≤J := by apply Classical.byContradiction; intro short have small : J-s≤n := by omega let 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] <;> omega have off := nonbottom j inRow change ts.bottom (c (s+column n odd j)).a.tag=false at off rw [atJ] at off simp [Return,off] at ret obtain ⟨low,V⟩ := next_row law c arr cont funct row nonbottom obtain ⟨below⟩ := ih (J-(s+n+1)) (by omega) (s+n+1) n (!odd) nextLe (by omega) low let t : Nat → Nat → Tag | 0 => tag | i+1 => below.t i refine ⟨⟨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 jl cases i with | zero => omega | succ i => cases i with | zero => change ts.top (below.t 0 j)=false rw [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 directional functionality 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) := by obtain ⟨k,ret⟩ := later_return c arr cont 0 simp only [Nat.zero_add] at ret have start := return_target _ (arr k) ret rw [cont] at start let s := k+1 obtain ⟨n,row⟩ := first_row law c arr cont s start.2.1 start.2.2.1 obtain ⟨off,ending⟩ := later_return c arr cont s have 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) row refine ⟨⟨box.h,n,box.t,box.ok,box.horizontal,box.vertical,box.l,box.r,?_,box.b⟩⟩ intro i j le jl cases 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 P455GridAssembly end /- Begin Problem455PaddedWordSlots (from finite-semigroup-identity-bases). -/ section namespace P455PaddedWord open P455PaddedMatchings P455PaddedPorts P455RectangleRank Problem455.Slots P455Witness def text (h w k : Nat) (tag : Nat→Tag) (bit : Nat→Bool) := word (w*h) (middle h w k tag) (tail (w*h)) bit theorem range_cut {i n : Nat} (lt : iletters (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 := by unfold portChunks conv => 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 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 omega by_cases early : d=0 ∨ d=1 · obtain ⟨post,cut⟩ := private_cut tag bits lt rw [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 := by unfold slotStart at sl rcases 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⟩ := place obtain ⟨post,cut⟩ := phase_cut tag bits p rw [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 (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 P455PaddedWord end /- Begin Problem455GuardProduct (from finite-semigroup-identity-bases). -/ section namespace P455GuardProduct open P455Witness P455SlotProduct P455SourceFamilies P455CrossedSupport open P455PortReflection P455SlotSaturation P455DefectRename P455FirstRewrite open Problem455.Slots abbrev W := List Nat inductive Guard where | slot (s : SlotCertificate) | func (f : FunctionalityCertificate) def Guard.anchor : Guard → Node | .slot s => s.anchor | .func f => f.anchor def Guard.bit : Guard → Bool | .slot s => s.bit | .func f => f.bit def Guard.isFunc : Guard → Bool | .slot _ => false | .func _ => true def Guard.query (g : Guard) (r : Nat) (ts : Tiles) : Query := match g with | .slot s => s.query r | .func f => f.query ts def 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 43 def words (r : Nat) (kind : Bool) := Problem455Finite.wordsUpTo (List.range (width kind)) (width kind*r) structure Index (r : Nat) (allow : Tag → Prop) (ts : Tiles) where kind : Bool pos : Fin (words r kind).length a : 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.pos def 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.T def product (r : Nat) (allow : Tag → Prop) (ts : Tiles) : Model (Carrier r allow ts) where op := 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) := by let 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) := by induction z with | nil => rfl | cons a z ih => change P455Quotient.mul i.R i.cap (val a i) _ = _ rw [ih]; rfl exact (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 := by let T := (select keep u).map keep.idxOf have labels : ∀ a ∈ T, a < width n := by intro a ha; obtain ⟨b,hb,rfl⟩ := List.mem_map.mp ha exact Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (kept hb)) len obtain ⟨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 coord have eqT : T = i.T := eq.symm change P455Quotient.ofWord i.R i.T T = _ at coord rw [eqT] at coord have good : P455Quotient.Good i.R i.T i.T := ⟨_,.refl _,[],[],by simp⟩ have path := ((P455Quotient.same_nonzero_class i.R good).mp coord).2 have 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 pr change select [keep.idxOf x,keep.idxOf y] ((select keep u).map keep.idxOf) = _ at pr rw [← binary_select_map keep u ho hm, ← binary_select_map keep w ho hm] at pr have k (z : W) (c : Nat) (hc : c ∈ select [x,y] z) : c ∈ keep := by rcases (by simpa using kept hc : c=x ∨ c=y) with e|e · exact e ▸ ho · exact e ▸ hm have decoded := congrArg (List.map (decode keep)) pr simpa only [decode_map (k u),decode_map (k w)] using decoded private theorem free_all (qs : List Query) (all : ∀ q ∈ qs, markFree q = true) : markFree (allQ qs) = true := by induction 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 := by induction xs with | nil => rfl | cons a xs ih => have every : markFree (allQ (xs.map (Query.separate a))) = true := by apply free_all; intro q h; obtain ⟨_,_,rfl⟩ := List.mem_map.mp h; rfl simp [differentBlocks,markFree,ih,every] theorem free_term (r o i : Nat) (d : SlotDefect) : markFree (terminalSlot r o i d) = true := by cases d with | deficient => rfl | overflow xs => have terms : markFree (allQ (xs.map fun a => Query.both (.count a r) (.slot o i a))) = true := by apply free_all; intro q h; obtain ⟨_,_,rfl⟩ := List.mem_map.mp h; rfl simp [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 := by induction p generalizing a with | nil => exact free_term .. | cons bc p ih => have ct : markFree (contact r a bc.1 bc.2) = true := by cases c : bc.2 with | record tag rev => cases rev <;> rfl | port phase rev => rfl simp [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 := by cases 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 <;> rfl theorem 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) := by have same : g.withBit g.bit = g := by cases g <;> rfl have parts := ok rw [← same,split_query] at parts obtain ⟨ne,length,tag,_,eq⟩ := parts.1 have 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'⟩ := obs have tail : Holds r allow noMark u (g.tail r ts) := remark (tail_free ..) parts.2 have 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 P455GuardProduct end /- Begin Problem455UniformCross (from finite-semigroup-identity-bases). -/ section namespace P455UniformCross open P455Witness P455SourceFamilies P455SourceTheorem P455OriginalWalk open P455ContactLift P455CrossedSupport P455SingletonEvaluation Problem455.Slots theorem 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 := by have capU : P455Closure.Cap r U := by intro a by_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 flip have pos : 0 < r := by omega obtain ⟨seed,side,img⟩ := choose_seed c s false cross have 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 := by rw [back] intro t _ refine ⟨True.intro,?_⟩ intro i _ a occ obtain ⟨j,seen⟩ := occ exact ⟨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 tester s false seed hr source exp (back.symm ▸ capU) guard rw [back] at read let R := rules r allow mark have ev := P455Quotient.eval_rep R capT val U h reps have good := (P455Quotient.nonzero_iff R).mp (ev ▸ live) have capH := P455Quotient.good_cap R capT good let d := donor U h r refine ⟨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 cmp theorem 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 := by let R := rules r allow mark let 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 cross rw [P455Quotient.eval_rep R capT val U h (fun _ _ => rfl)] exact (P455Quotient.nonzero_iff R).mpr good end P455UniformCross end /- Begin Problem455PaddedAssembly (from finite-semigroup-identity-bases). -/ section namespace P455PaddedTiles open P455Witness variable {n : Nat} {M : MachineTable n} private theorem neg_of_ne {a b : Bool} (h : a≠b) : b= !a := by cases a <;> cases b <;> simp_all theorem system_laws (n : Nat) : P455GridRows.Laws (system n) where horiz := by rintro _ _ ⟨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 := by rintro _ _ ⟨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 := by by_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 := by cases b <;> by_cases hp : p <;> simp_all def from_assembly (A : P455GridAssembly.Rectangle (allowed M) (system n)) : Rectangle M (A.width+1) (A.height+1) where positiveW := by omega positiveH := by omega tag := A.tile eligible := 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 := by intro y iy x jx have hy : y≤A.height := by omega have hx : x≤A.width := by omega have tops := A.top y x hy hx have lefts := A.left y x hy hx refine ⟨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 iy induction y with | zero => obtain ⟨p,eq,ok⟩ := A.allowed 0 x (by omega) hx have top := (A.top 0 x (by omega) hx).mpr rfl rw [←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 jx induction x with | zero => obtain ⟨p,eq,ok⟩ := A.allowed y 0 hy (by omega) have left := (A.left y 0 hy (by omega)).mpr rfl rw [←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+1 cells, 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 := by simpa using read_trace (from_assembly A) /-- Infinite continuation of literal source-word arrows now yields a 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) := by obtain ⟨R⟩ := P455GridAssembly.rectangle_of_trace (system_laws n) c edges cont functional exact ⟨R.width+1,R.height,⟨assembly_trace R⟩⟩ end P455PaddedTiles end /- Begin Problem455PaddedOrders (from finite-semigroup-identity-bases). -/ section namespace P455PaddedWord open P455PaddedPorts P455PaddedMatchings P455RectangleRank P455Witness Problem455.Slots private theorem in_stamp (n : Nat→Nat) (w : List Nat) {a j : Nat} (lo : n a≤j) (hi : j0) l := in_stamp _ l (by omega) (by simpa using inL) have right : (b,j)∈stamp (advance (fun _=>0) l) t := by apply in_stamp <;> simp [advance,List.count_append] at * <;> omega exact ((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 dsimp <;> omega · obtain ⟨post,cut⟩ := private_cut tag bits last have total := word_count (k:=k) size tag bits j b rb rw [if_pos last] at total change (text h w k tag bits).count b=_ at total rw [cut,List.append_assoc] at total ⊢ apply sees_across · simpa [private_counts i a ra,lt] using ei · simp [private_counts j b rb] · omega theorem early_groups {h w k : Nat} (size : 1 early_order size tag bits allow mark e lj ra rb (by decide) (by decide)) · apply Or.inr exact (P455PortReflection.earlyBefore_iff ..).mpr (fun _ ra _ rb => early_order size tag bits allow mark (by omega : j(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 columnCells rw [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) := by unfold 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 dsimp <;> omega end P455PaddedWord end /- Begin Problem455GuardRename (from finite-semigroup-identity-bases). -/ section namespace P455GuardRename open P455Witness P455Paths P455ContactLift P455SourceFamilies P455DefectRename open P455ContactReflection P455PortReflection Problem455.Slots Problem455Swap private theorem bigram_map (d : Nat → Nat) (inj : Injects d) (a b : Nat) (w : W) : bigram (d a) (d b) (w.map d) = bigram a b w := by induction w with | nil => rfl | cons c t ih => cases t with | nil => simp [bigram,hit] | cons z t => change hit _ _ (some (d c)) (some (d z)) + _ = hit _ _ (some c) (some z) + _ have ca : d c = d a ↔ c = a := ⟨fun e => inj e,congrArg d⟩ have zb : d z = d b ↔ z = b := ⟨fun e => inj e,congrArg d⟩ simp only [hit,Option.some.injEq,ca,zb,← ih,List.map_cons] private theorem link_names {r a b : Nat} {w : W} (hr : 0 < r) (edge : Link r w a b) : a ∈ w ∧ b ∈ w := by have l := out_bound a b (b+1) (by omega) w have r' := in_bound a (a+1) b (by omega) w have tail := tail_occ_le b w unfold Link at edge rw [Problem455BlockBridge.occ_count] at l tail rw [Problem455BlockBridge.occ_count] at r' rw [Problem455BlockBridge.occ_count] at tail exact ⟨List.count_pos_iff.mp (by omega), List.count_pos_iff.mp (by omega)⟩ /-- A renamed walk may be presented with arbitrary intermediate Nat labels. Positivity forces each intermediate endpoint of each literal link to occur in the mapped word, hence to have a preimage. -/ theorem sameBlock_reflect {r : Nat} (hr : 0 < r) (d : Nat → Nat) (inj : Injects d) (w : W) (a b : Nat) (same : SameBlock r (w.map d) (d a) (d b)) : SameBlock r w a b := by obtain ⟨ac,bc,path⟩ := same simp only [Problem455BlockBridge.occ_count,count_rename d inj] at ac bc refine ⟨Problem455BlockBridge.occ_count .. |>.trans ac,Problem455BlockBridge.occ_count .. |>.trans bc,?_⟩ have lift (j) (p : Joined (Link r (w.map d)) (d a) j) : ∀ b', j = d b' → Joined (Link r w) a b' := by induction p with | refl => intro b' e; have ab := inj e; exact ab ▸ Joined.refl _ | @extend y z prev last ih => intro b' eq; subst z have mem : y ∈ w.map d := last.elim (fun xy => (link_names hr xy).1) (fun yx => (link_names hr yx).2) obtain ⟨c,_,rfl⟩ := List.mem_map.mp mem apply Joined.extend (ih c rfl) simpa only [Link,bigram_map d inj] using last exact lift _ path b rfl theorem rename_separate {r : Nat} (hr : 0 < r) (d : Nat → Nat) (inj : Injects d) (w : W) (a b : Nat) (sep : ¬ SameBlock r w a b) : ¬ SameBlock r (w.map d) (d a) (d b) := fun same => sep (sameBlock_reflect hr d inj w a b same) private theorem rename_slot_atom {r allow src dst w o i a} (d : Nat → Nat) (inj : Injects d) (h : Holds r allow src w (.slot o i a)) : Holds r allow dst (w.map d) (.slot (d o) i (d a)) := by obtain ⟨idx,j,seen⟩ := h exact ⟨idx,j,rename_sees d inj seen⟩ theorem rename_terminal {r allow src dst w o i} (hr : 0 < r) (d : Nat → Nat) (inj : Injects d) (kind : SlotDefect) (h : Holds r allow src w (terminalSlot r o i kind)) : Holds r allow dst (w.map d) (terminalSlot r (d o) i (sendDefect d kind)) := by cases kind with | deficient a => exact ⟨rename_slot_atom d inj h.1,by simpa only [Holds,count_rename d inj] using h.2⟩ | overflow xs => have old := (P455TerminalTransfer.block_separation _).mp h.2.1 have mapped : ((o :: xs).map d).Pairwise (fun a b => ¬ SameBlock r (w.map d) a b) := old.map d (fun a b sep => rename_separate hr d inj w a b sep) refine ⟨by simpa [P455Witness.Holds] using h.1,(P455TerminalTransfer.block_separation _).mpr mapped,?_,True.intro⟩ apply (allQ_iff _).mpr intro q mem obtain ⟨b,inList,rfl⟩ := List.mem_map.mp mem obtain ⟨a,ha,rfl⟩ := List.mem_map.mp inList have orig : Holds r allow src w (.both (.count a r) (.slot o i a)) := ((allQ_iff _).mp h.2.2.1) _ (List.mem_map_of_mem ha) exact ⟨(count_rename d inj w a).trans orig.1,rename_slot_atom d inj orig.2⟩ theorem rename_slot {r allow src w} (d : Nat → Nat) (inj : Injects d) (s : SlotCertificate) (h : Holds r allow src w (s.query r)) : Holds r allow (markNode (sendSlot d s).anchor) (w.map d) ((sendSlot d s).query r) := by have length : s.anchor.tag.length + 16 = r := h.1.2.1 obtain ⟨len,walk,term⟩ := slot_route s h have start' : picked (sendSlot d s) = d (picked s) := by cases side : s.startAtMate <;> simp [sendSlot,picked,sendNode,side] refine ⟨rename_marked d inj s.anchor s.bit h.1,by simpa [sendSlot,relabel,P455Witness.Holds] using len,?_,True.intro⟩ apply (route_iff ..).mpr change 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] exact ⟨rename_walk d inj _ _ walk, rename_terminal (by omega) d inj _ term⟩ private theorem rename_early {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (xs ys : W) (h : Holds r allow src w (earlyBefore xs ys)) : Holds r allow dst (w.map d) (earlyBefore (xs.map d) (ys.map d)) := by apply (earlyBefore_iff _ _).mpr rintro x hx y hy obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hx obtain ⟨b,hb,rfl⟩ := List.mem_map.mp hy exact rename_order d inj [(a,2),(b,0)] ((earlyBefore_iff _ _).mp h a ha b hb) theorem rename_port {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (phase : Nat) (a b : Node) (port : Holds r allow src w (orientedPort phase a b)) : Holds r allow dst (w.map d) (orientedPort phase (sendNode d a) (sendNode d b)) := by refine ⟨rename_record d inj port.1,rename_record d inj port.2.1,?_,?_,True.intro⟩ · rcases port.2.2.1 with f | rev · exact Or.inl (rename_early d inj (roles a) (roles b) f) · exact Or.inr (rename_early d inj (roles b) (roles a) rev) · let i := 3+2*phase exact rename_order d inj [(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)] port.2.2.2.1 private theorem rename_rightward {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (ts : Tiles) (a b : Node) (h : Holds r allow src w (rightward ts a b)) : Holds r allow dst (w.map d) (rightward ts (sendNode d a) (sendNode d b)) := ⟨h.1,rename_port d inj _ a b h.2.1,rename_order d inj [(a.owner,13+a.tag.length), (b.owner,13+a.tag.length)] h.2.2.1,True.intro⟩ private theorem rename_downward {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (ts : Tiles) (a b : Node) (h : Holds r allow src w (downward ts a b)) : Holds r allow dst (w.map d) (downward ts (sendNode d a) (sendNode d b)) := ⟨h.1,rename_port d inj _ a b h.2⟩ theorem rename_neighbor {r allow src dst w} (d : Nat → Nat) (inj : Injects d) (ts : Tiles) (a b : Node) (dir : Dir) (h : Holds r allow src w (neighbor ts a b dir)) : Holds r allow dst (w.map d) (neighbor ts (sendNode d a) (sendNode d b) dir) := by cases dir <;> first | exact rename_rightward d inj _ _ _ h | exact rename_downward d inj _ _ _ h theorem rename_func {r allow src w} (d : Nat → Nat) (inj : Injects d) (ts : Tiles) (f : FunctionalityCertificate) (h : Holds r allow src w (f.query ts)) : Holds r allow (markNode (sendFunc d f).anchor) (w.map d) ((sendFunc d f).query ts) := by have length : f.anchor.tag.length + 16 = r := h.1.2.1 refine ⟨rename_marked d inj f.anchor f.bit h.1,rename_neighbor d inj ts f.anchor f.b f.dir h.2.1, rename_neighbor d inj ts f.anchor f.c f.dir h.2.2.1,?_,True.intro⟩ cases e : f.distinguishMate <;> simpa [sendFunc,sendNode,e,Holds] using rename_separate (by omega) d inj w _ _ h.2.2.2.1 /-- Use keep.idxOf only on the projected literal alphabet. The total injective extension may send unused names outside the bounded alphabet. -/ theorem canonical_slot {r allow src u} (keep : W) (s : SlotCertificate) (ho : s.anchor.owner ∈ keep) (hm : s.anchor.mate ∈ keep) (h : Holds r allow src (select keep u) (s.query r)) : ∃ s' : SlotCertificate, s'.anchor.owner = keep.idxOf s.anchor.owner ∧ s'.anchor.mate = keep.idxOf s.anchor.mate ∧ s'.bit = s.bit ∧ s'.defect = sendDefect (extend keep) s.defect ∧ Holds r allow (markNode s'.anchor) ((select keep u).map keep.idxOf) (s'.query r) := by let d := extend keep have eq := extend_map (keep := keep) (w := select keep u) (fun _ m => kept m) exact ⟨sendSlot d s,by simp [sendSlot,sendNode,d,extend,ho],by simp [sendSlot,sendNode,d,extend,hm], rfl,rfl, by simpa only [← eq,d] using rename_slot d (extend_inj keep) s h⟩ theorem canonical_func {r allow src u} (keep : W) (ts : Tiles) (f : FunctionalityCertificate) (ho : f.anchor.owner ∈ keep) (hm : f.anchor.mate ∈ keep) (h : Holds r allow src (select keep u) (f.query ts)) : ∃ f' : FunctionalityCertificate, f'.anchor.owner = keep.idxOf f.anchor.owner ∧ f'.anchor.mate = keep.idxOf f.anchor.mate ∧ f'.bit = f.bit ∧ Holds r allow (markNode f'.anchor) ((select keep u).map keep.idxOf) (f'.query ts) := by let d := extend keep have eq := extend_map (keep := keep) (w := select keep u) (fun _ m => kept m) exact ⟨sendFunc d f,by simp [sendFunc,sendNode,d,extend,ho],by simp [sendFunc,sendNode,d,extend,hm], rfl, by simpa only [← eq,d] using rename_func d (extend_inj keep) ts f h⟩ private theorem cap_idx {r : Nat} {u keep : W} (h : P455Closure.Cap r (select keep u)) : P455Closure.Cap r ((select keep u).map keep.idxOf) := by rw [← extend_map (keep := keep) (w := select keep u) (fun _ m => kept m)] exact cap_rename _ (extend_inj keep) h /-- The actual bounded one-mark guard sent to the finite product. The projected word, marked roles and bound are recovered from the original certificate for each of the deficient, overflow and duplicate-port cases. -/ theorem bounded_guard {r allow u} (cap : P455Closure.Cap r u) (ts : Tiles) (orig : P455GuardProduct.Guard) (ok : Holds r allow (markNode orig.anchor) u (orig.query r ts)) : ∃ (keep : W) (g : P455GuardProduct.Guard), keep.length ≤ P455GuardProduct.width orig.isFunc ∧ orig.anchor.owner ∈ keep ∧ orig.anchor.mate ∈ keep ∧ g.isFunc = orig.isFunc ∧ g.anchor.owner = keep.idxOf orig.anchor.owner ∧ g.anchor.mate = keep.idxOf orig.anchor.mate ∧ P455Closure.Cap r ((select keep u).map keep.idxOf) ∧ Holds r allow (markNode g.anchor) ((select keep u).map keep.idxOf) (g.query r ts) := by cases orig with | slot s => change Holds r allow (markNode s.anchor) u (s.query r) at ok cases kind : s.defect with | deficient bad => obtain ⟨len,walk,term⟩ := slot_route s ok rw [kind] at term obtain ⟨⟨index,inside⟩,defic⟩ := term let last := endpoint (picked s) s.steps have near : Near r allow (markNode s.anchor) u (picked s) last 6 := ⟨s.steps,walk,rfl,len⟩ obtain ⟨keep,s',len',ho,hm,xa,yb,_,_,_,cp,test⟩ := canonical_defect cap s.anchor s.bit s.startAtMate last s.terminalIndex bad ok.1 near index inside defic exact ⟨keep,.slot s',Nat.le_trans len' (by decide : 9 ≤ 43),ho,hm,rfl,xa,yb,cp,test⟩ | overflow xs => have length : s.anchor.tag.length + 16 = r := ok.1.2.1 obtain ⟨keep,len,ho,hm,_,cp,projected⟩ := P455OtherProjection.bounded_overflow (by omega) cap s xs kind ok obtain ⟨s',xa,yb,_,_,test⟩ := canonical_slot keep s ho hm projected exact ⟨keep,.slot s',len,ho,hm,rfl,xa,yb,cap_idx cp,test⟩ | func f => change Holds r allow (markNode f.anchor) u (f.query ts) at ok have length : f.anchor.tag.length + 16 = r := ok.1.2.1 obtain ⟨keep,len,mem,cp,projected⟩ := P455OtherProjection.bounded_functionality (by omega) cap ts f ok have ho := mem f.anchor.owner (by simp [roles]) have hm := mem f.anchor.mate (by simp [roles]) obtain ⟨f',xa,yb,_,test⟩ := canonical_func keep ts f ho hm projected exact ⟨keep,.func f',len,ho,hm,rfl,xa,yb,cap_idx cp,test⟩ end P455GuardRename end /- Begin Problem455GuardSubproduct (from finite-semigroup-identity-bases). -/ section namespace P455GuardSubproduct open P455Witness P455SlotProduct P455GuardProduct P455DefectProjection open P455FirstRewrite abbrev W := List Nat theorem letters {A : W} {w : W} {k : Nat} (mem : w ∈ Problem455Finite.wordsUpTo A k) : ∀ a ∈ w, a ∈ A := by induction k generalizing w with | zero => simp [Problem455Finite.wordsUpTo] at mem; simp [mem] | succ k ih => rcases List.mem_cons.mp mem with e|rest · simp [e] · obtain ⟨x,hx,m⟩ := List.mem_flatMap.mp rest obtain ⟨v,vm,rfl⟩ := List.mem_map.mp m exact fun a ha => (List.mem_cons.mp ha).elim (fun e => e ▸ hx) (ih vm a) theorem represented {r allow ts} (i : P455SlotProduct.Index r allow) : ∃ j : P455GuardProduct.Index r allow ts, j.T = i.T ∧ j.a.val = i.a.val ∧ j.b.val = i.b.val := by obtain ⟨s,d,_,ax,ay,obs⟩ := i.test have pos : i.T ∈ templates r := List.get_mem .. have ns (a : Nat) (h : a ∈ i.T) : a < 9 := List.mem_range.mp (letters pos a h) have sub (a : Nat) (h : a ∈ i.T) : a < width false := by have := ns a h; change a < 43; omega obtain ⟨n,eq⟩ := List.get_of_mem (Problem455Finite.covered (List.range (width false)) _ i.T (capped_length _ _ i.cap sub) (fun a ha => List.mem_range.mpr (sub a ha))) let a : Fin (width false) := ⟨i.a.val,by have := i.a.isLt; change _ < 43; omega⟩ let b : Fin (width false) := ⟨i.b.val,by have := i.b.isLt; change _ < 43; omega⟩ let g : Guard := .slot s let j : P455GuardProduct.Index r allow ts := ⟨false,n,a,b,eq.symm ▸ i.cap, g,rfl,ax,ay,eq.symm ▸ obs⟩ exact ⟨j,eq,rfl,rfl⟩ /-- The designated projection valuation is sufficient to force saturation. This version only requests validity in the full guard product and uses the actual bounded tester produced for the bad slot. -/ theorem uniform {r allow mark ts u w x y} (hr : P455Closure.Cap r u) (ident : (product r allow ts).Valid u w) (flip : P455CrossedSupport.ClosedFlip r allow u x y) (changed : Problem455.Slots.select [x,y] u ≠ Problem455.Slots.select [x,y] w) : P455CrossedSupport.UniformSlots r allow mark u x y := by obtain ⟨tag,bit,marked⟩ := flip_anchor hr flip let n : Node := ⟨x,y,tag⟩ intro t near i slot bad occ apply Classical.byContradiction intro ne have lt : u.count bad < r := by have := hr bad; omega have route : ∃ s : Bool, P455Paths.Near r allow mark u (if s then n.mate else n.owner) t 6 := near.elim (fun h => ⟨false,h⟩) (fun h => ⟨true,h⟩) obtain ⟨s,h⟩ := route obtain ⟨keep,c,len,ho,hm,ax,ay,_,_,_,capT,q⟩ := P455DefectRename.canonical_defect hr n bit s t i bad marked h slot occ lt apply changed exact test_projects ident keep ho hm (.slot c) false rfl (by change keep.length ≤ 43; omega) ax ay capT q end P455GuardSubproduct end /- Begin Problem455ConstantLayout (from finite-semigroup-identity-bases). -/ section namespace P455ConstantLayout open P455Witness P455SourceFamilies P455CrossedSupport P455SingletonEvaluation open P455Uncrossed P455MarkedPath abbrev W := List Nat /-- One actual literal frame flip, with its two source names among the designated cell pairs. All surrounding contexts count as part of the word. -/ def Flip (r : Nat) (allow : Tag → Prop) (used : Nat → Nat → Prop) (s t : W) := ∃ (x y : Nat) (f : P455Closure.Frame Nat) (b : Bool) (l k : W), used x y ∧ f.p = [x] ∧ f.q = [y] ∧ f.Valid r allow (fun _ _ => False) ∧ s = side f l k b ∧ t = side f l k (!b) abbrev Chain (r : Nat) (allow : Tag → Prop) (used : Nat → Nat → Prop) := P455Quotient.Walk (Flip r allow used) theorem contents {r allow used U V} (path : Chain r allow used U V) (a : Nat) : a ∈ U ↔ a ∈ V := by induction path with | refl => rfl | snoc _ mv ih => obtain ⟨x,y,f,b,l,k,_,_,_,_,rfl,rfl⟩ := mv exact ih.trans (same_letters f l k b a) theorem clear_chain {r allow used mark T U V} (capT : P455Quotient.Cap r T) (path : Chain r allow used U V) (h : Nat → W) (clear : ∀ x y, used x y → Unmarked mark h x y) : P455Quotient.ofWord (rules r allow mark) T (U.flatMap h) = P455Quotient.ofWord (rules r allow mark) T (V.flatMap h) := by induction path with | refl => rfl | snoc _ mv ih => obtain ⟨x,y,f,b,l,k,pair,hp,hq,valid,rfl,rfl⟩ := mv exact ih.trans (uncrossed_words capT f l k b x y hp hq valid h (clear x y pair)) /-- The endpoint choice is shared across all checked pairs. No saturation, compression, or absence of violations is required at mixed intermediates. -/ structure Layout (r : Nat) (allow : Tag → Prop) (ts : Tiles) (endWord : Bool → W) where used : Nat → Nat → Prop path : Chain r allow used (endWord false) (endWord true) uniform : ∀ b, ∀ a ∈ endWord b, (endWord b).count a = r compressed : ∀ b, Compressed r (endWord b) frame : ∀ b x y, used x y → ClosedFlip r allow (endWord b) x y clean : ∀ b x y, used x y → ¬ Violation r allow ts (endWord b) x y /-- A generic quotient calculation. A crossing need be ruled out solely at the live endpoint, for the very same representatives used along the path. -/ theorem compare {r allow used mark T} (capT : P455Quotient.Cap r T) (c : Certificate) (only : MarksOnly mark c) (endWord : Bool → W) (path : Chain r allow used (endWord false) (endWord true)) (val : Nat → P455Quotient.Q (rules r allow mark) T) (reject : ∀ (b : Bool) (h : Nat → W), P455Quotient.Good (rules r allow mark) T ((endWord b).flatMap h) → ∀ x y, used x y → ∀ s, ¬ Crosses (markedRecord c s) h x y) : P455Quotient.eval (rules r allow mark) capT val (endWord false) = P455Quotient.eval (rules r allow mark) capT val (endWord true) := by classical apply Classical.byContradiction intro diff let R := rules r allow mark have live : ∃ b : Bool, P455Quotient.eval R capT val (endWord b) ≠ P455Quotient.zero R T := by by_cases h : P455Quotient.eval R capT val (endWord false) ≠ P455Quotient.zero R T · exact ⟨false,h⟩ · exact ⟨true,fun e => diff ((Classical.not_not.mp h).trans e.symm)⟩ obtain ⟨b,nz⟩ := live have existsRep (a : Nat) (ha : a ∈ endWord b) := P455Quotient.nonzero_representative R (val a) (P455Quotient.live_inputs R capT val _ nz a ha) let h (a : Nat) := if yes : a ∈ endWord b then (existsRep a yes).choose else [] have rep (a) (mem : a ∈ endWord b) : P455Quotient.ofWord R T (h a) = val a := by simpa only [h,dif_pos mem] using (existsRep a mem).choose_spec.2 have value := P455Quotient.eval_rep R capT val _ h rep have good := (P455Quotient.nonzero_iff R).mp (value ▸ nz) have clear (x y) (use : used x y) : Unmarked mark h x y := by intro a ma z mz have nope : ¬ (mark a z ∨ mark z a) := by intro hit obtain ⟨s,cross⟩ := pick_cross only ⟨a,ma,z,mz,hit⟩ exact reject b h good x y use s cross exact ⟨fun e => nope (.inl e),fun e => nope (.inr e)⟩ have support (s : Bool) (a) (m : a ∈ endWord s) : a ∈ endWord b := by cases s <;> cases b · exact m · exact (contents path a).mp m · exact (contents path a).mpr m · exact m apply diff rw [P455Quotient.eval_rep R capT val (endWord false) h (fun a m => rep a (support false a m)), P455Quotient.eval_rep R capT val (endWord true) h (fun a m => rep a (support true a m))] exact clear_chain capT path h clear /-- Marked Section 8 identity conditional on the actual finite layout and its two endpoint geometries. Every live crossed evaluation transfers one of the three designated tester families to that same constant endpoint. -/ theorem marked_equal {r allow ts mark T} (capT : P455Quotient.Cap r T) (endWord : Bool → W) (layout : Layout r allow ts endWord) (c : Certificate) (only : MarksOnly mark c) (tester : Holds r allow mark T (c.query r ts)) (val : Nat → P455Quotient.Q (rules r allow mark) T) : P455Quotient.eval (rules r allow mark) capT val (endWord false) = P455Quotient.eval (rules r allow mark) capT val (endWord true) := by apply compare capT c only endWord layout.path val intro b h good x y used s cross apply layout.clean b x y used exact P455UniformCross.crossed_word capT ts c tester (endWord b) (layout.uniform b) (layout.compressed b) x y (layout.frame b x y used) h good s cross end P455ConstantLayout end /- Begin Problem455ActualGuards (from finite-semigroup-identity-bases). -/ section namespace P455ActualGuards open P455Witness P455SourceFamilies P455GuardProduct P455SingletonEvaluation open P455SlotSaturation P455CrossedSupport Problem455.Slots P455Paths P455SupportBound abbrev W := List Nat theorem matched_change {x y u w} (n : Node) (m : Matches n x y) (diff : select [x,y] u ≠ select [x,y] w) : select [n.owner,n.mate] u ≠ select [n.owner,n.mate] w := by rcases m with ⟨a,b⟩|⟨a,b⟩ · simpa only [a,b] using diff · simpa only [a,b,select_pair_symm y x] using diff theorem no_guard {r allow ts u₀ w v x y} (cap₀ : P455Closure.Cap r u₀) (identity : (product r allow ts).Valid u₀ w) (changed : select [x,y] u₀ ≠ select [x,y] w) (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ v) (g : Guard) (anchor : Matches g.anchor x y) : ¬ Holds r allow (markNode g.anchor) v (g.query r ts) := by intro bad obtain ⟨b,back⟩ := replay (path.symm P455Closure.Move.symm) g bad let c := g.withBit b have same : c.anchor = g.anchor := by cases g <;> rfl have q : Holds r allow (markNode c.anchor) u₀ (c.query r ts) := same.symm ▸ back obtain ⟨keep,f,len,ho,hm,kind,ax,ay,capT,read⟩ := P455GuardRename.bounded_guard cap₀ ts c q exact (matched_change c.anchor (same ▸ anchor) changed) (test_projects identity keep ho hm f c.isFunc kind len ax ay capT read) theorem capacity {r allow mark ts u₀ w v x y} (cap₀ : P455Closure.Cap r u₀) (identity : (product r allow ts).Valid u₀ w) (changed : select [x,y] u₀ ≠ select [x,y] w) (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ v) (flip₀ : ClosedFlip r allow u₀ x y) (capV : P455Closure.Cap r v) (flipV : ClosedFlip r allow v x y) (cmp : Compressed r v) : Capacity r allow mark v x y 4 := by have unif : UniformSlots r allow mark v x y := uniform_variant path (P455GuardSubproduct.uniform cap₀ identity flip₀ changed) apply capacity_of_no_overflow unif cmp intro t ball i sl xs read obtain ⟨tag,bit,marked⟩ := P455SlotProduct.flip_anchor capV flipV let n : Node := ⟨x,y,tag⟩ have hit : ∃ side : Bool, Near r allow mark v (if side then n.mate else n.owner) t 6 := ball.elim (fun h => ⟨false,h⟩) (fun h => ⟨true,h⟩) obtain ⟨side,p,walk,ep,len⟩ := hit let s : SlotCertificate := ⟨n,bit,side,p,i,.overflow xs⟩ apply no_guard cap₀ identity changed path (.slot s) (.inl ⟨rfl,rfl⟩) refine ⟨marked,len,?_,True.intro⟩ apply (route_iff ..).mpr exact ⟨remark_walk _ _ walk,ep.symm ▸ P455PortReflection.remark (P455GuardProduct.free_term r t i (.overflow xs)) read⟩ def EdgeViolation (r : Nat) (allow : Tag → Prop) (ts : Tiles) (v : W) (x y : Nat) := ∃ (e : EdgeCertificate) (s : Bool), Matches (markedRecord (.edge e) s) x y ∧ Holds r allow (P455SourceTheorem.sourceMarks id (.edge e)) v (e.query ts) theorem only_edge {r allow ts u₀ w v x y} (cap₀ : P455Closure.Cap r u₀) (identity : (product r allow ts).Valid u₀ w) (changed : select [x,y] u₀ ≠ select [x,y] w) (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ v) (bad : Violation r allow ts v x y) : EdgeViolation r allow ts v x y := by obtain ⟨c,s,anchor,read⟩ := bad cases c with | slot p => exact False.elim (no_guard cap₀ identity changed path (.slot p) anchor read) | functionality f => exact False.elim (no_guard cap₀ identity changed path (.func f) anchor read) | edge e => exact ⟨e,s,anchor,read⟩ end P455ActualGuards end /- Begin Problem455LocalIdentity (from finite-semigroup-identity-bases). -/ section /- Every distinguishing marked quotient valuation produces a forbidden incident edge on one of the actual source words. The two one-mark families have already been excluded by endpoint identity validity. -/ namespace P455LocalIdentity open P455Witness P455SourceFamilies P455CrossedSupport P455SingletonEvaluation open P455SlotSaturation P455GuardProduct P455ActualGuards P455Uncrossed open P455MarkedPath P455Compression Problem455.Slots abbrev W := List Nat theorem marked_equal {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 : (product r allow ts).Valid 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)) (feasible : ∀ b, ¬ EdgeViolation r allow ts (side f l k b) x y) (v : Nat → P455Quotient.Q (rules r allow mark) T) : let keep := retained r allow noMark (side f l k false) x y P455Quotient.eval (rules r allow mark) capT v (small (side f l k false) keep) = P455Quotient.eval (rules r allow mark) capT v (small (side f l k true) keep) := by let mv : P455Closure.Move r allow noMark (side f l k false) (side f l k true) := ⟨f,false,l,k,fv,rfl,rfl,capF⟩ have per := P455RetainedVariant.same_retained (mark := noMark) mv x y apply Classical.byContradiction intro neq have diff : P455Quotient.eval (rules r allow mark) capT v (ruleWord r allow noMark (side f l k false) x y) ≠ P455Quotient.eval (rules r allow mark) capT v (ruleWord r allow noMark (side f l k true) x y) := by intro eq apply neq dsimp only rw [P455RetainedVariant.small_congr_names (side f l k true) per] exact eq obtain ⟨b,bad⟩ := compare_uniform capT ts c only tester f l k x y hp hq fv capF u₀ (P455GuardSubproduct.uniform cap₀ identity flip₀ changed) path cmp v diff have pb : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ (side f l k b) := by cases b; exact path; exact .snoc path mv exact feasible b (only_edge cap₀ identity changed pb bad) theorem coordinate_eval (val : Nat → Carrier r allow ts) (i : Index r allow ts) (w : W) : (product r allow ts).eval val w i = P455Quotient.eval i.R i.cap (fun x => val x i) w := by induction w with | nil => rfl | cons x w ih => exact congrArg (P455Quotient.mul i.R i.cap (val x i)) ih theorem guard_coordinate (i : Index r allow ts) : ∃ c : Certificate, MarksOnly (P455SlotProduct.pairMark i.a i.b) c ∧ Holds r allow (P455SlotProduct.pairMark i.a i.b) i.T (c.query r ts) := by obtain ⟨g,_,ax,ay,obs⟩ := i.accepted cases g with | slot s => refine ⟨.slot s,?_,obs⟩ intro a b h; exact ⟨false,.inl ⟨ax.trans h.1.symm,ay.trans h.2.symm⟩⟩ | func f => refine ⟨.functionality f,?_,obs⟩ intro a b h; exact ⟨false,.inl ⟨ax.trans h.1.symm,ay.trans h.2.symm⟩⟩ end P455LocalIdentity end /- Begin Problem455PortUnique (from finite-semigroup-identity-bases). -/ section /- The one-mark guards genuinely give uniqueness of an entire target record, including its tag. The graph may therefore use nodes, not merely the unordered set of their two variable names. -/ namespace P455PortUnique open P455Witness P455Paths P455SourceFamilies P455CrossedSupport P455SlotSaturation open P455SingletonEvaluation P455ActualGuards P455GuardProduct P455PortReflection Problem455.Slots abbrev W := List Nat private theorem tag_unique {a b : Nat} (ne : a ≠ b) (s t : Tag) (p q : W) (len : s.length=t.length) (eq : s.flatMap (pair a b) ++ p = t.flatMap (pair a b) ++ q) : s=t := by induction s generalizing t with | nil => cases t <;> simp_all | cons x s ih => cases t with | nil => simp at len | cons y t => have lk : s.length=t.length := by simpa using len cases x <;> cases y <;> simp [List.flatMap_cons,pair,List.append_assoc,ne,Ne.symm ne] at eq ⊢ all_goals exact ih _ lk eq theorem node_unique {r allow mark w} (a b : Node) (own : a.owner=b.owner) (mate : a.mate=b.mate) (oa : Holds r allow mark w (typedNode a)) (ob : Holds r allow mark w (typedNode b)) : a=b := by obtain ⟨x,y,s⟩ := a; obtain ⟨z,t,v⟩ := b dsimp at own mate; subst z; subst t obtain ⟨ne,len,_,i,hi⟩ := oa obtain ⟨_,len',_,j,hj⟩ := ob change s.length+16=r at len; change v.length+16=r at len' have e : profile x y s i = profile x y v j := hi.symm.trans hj let pre := [x,x,y,x,y,y] ++ (List.replicate 5 [x,y,x,y]).flatten let post := fun bit => [x,y] ++ (pair x y bit ++ [x,y]) have eq : pre ++ (s.flatMap (pair x y) ++ post i) = pre ++ (v.flatMap (pair x y) ++ post j) := by simpa only [pre,post,profile,profilePrefix,List.append_assoc] using e have := tag_unique ne s v _ _ (by omega) (List.append_cancel_left eq) cases this; rfl theorem functional {r allow mark ts u₀ w v x y} (cap₀ : P455Closure.Cap r u₀) (valid : (product r allow ts).Valid u₀ w) (changed : select [x,y] u₀ ≠ select [x,y] w) (path : P455Quotient.Walk (P455Closure.Move r allow noMark) u₀ v) (cmp : Compressed r v) (n : Node) (side : Matches n x y) (recProof : Holds r allow mark v (typedNode n)) : P455GridRows.Functional r allow mark v ts n := by intro dir a b nb nc obtain ⟨ne,len,tag,bit,proj⟩ := recProof have anchor : Holds r allow (markNode n) v (markedNode n bit) := ⟨ne,len,tag,.inl ⟨rfl,rfl⟩,proj⟩ have roleeq (k : Bool) : roleOf k a = roleOf k b := by apply Classical.byContradiction; intro d let f : FunctionalityCertificate := ⟨n,bit,a,b,dir,k⟩ exact no_guard cap₀ valid changed path (.func f) side ⟨anchor,neighbor_remark nb,neighbor_remark nc,compressed_separates cmp d,True.intro⟩ exact node_unique a b (roleeq false) (roleeq true) (neighbor_target_record nb) (neighbor_target_record nc) end P455PortUnique end /- Begin Problem455BinaryEquality (from finite-semigroup-identity-bases). -/ section namespace P455BinaryEquality open P455Witness P455Closure P455Uncrossed P455SlotSaturation P455FirstTesters open Problem455.Slots abbrev W := List Nat def BinaryNames (T : W) := ∀ a ∈ T, a=0 ∨ a=1 def IsProfile (r : Nat) (allow : Tag → Prop) (T : W) := ∃ a b tag bit, a ≠ b ∧ tag.length+16 = r ∧ allow tag ∧ T = profile a b tag bit theorem binary_move_profile {r allow T V} (h : Move r allow noMark T V) (two : BinaryNames T) : IsProfile r allow T := by obtain ⟨f,bit,l,k,ok,rfl,_,cap⟩ := h let a := f.pHead let b := f.qLast have ap : a ∈ f.p := by simp [a,Frame.p] have bq : b ∈ f.q := by simp [b,Frame.q] have ab := fun e : a = b => ok.2.2.2.2.2.1 a ap (e ▸ bq) have hr : 0 < r := by have := ok.1; omega have mem (z : Nat) (hz : z ∈ f.p ∨ z ∈ f.q) : z ∈ l ++ f.core bit ++ k := by have count : (f.core bit).count z = r := by have cz := ok.2.2.2.2.2.2.2 z hz cases bit; exact cz; exact (f.count_core z true).trans cz have ins := List.count_pos_iff.mp (count.symm ▸ hr) simp [ins] have az := two _ (mem a (.inl ap)) have bz := two _ (mem b (.inr bq)) have all : ∀ z ∈ l ++ f.core bit ++ k, z=a ∨ z=b := by intro z hz; rcases az with ha|ha <;> rcases bz with hb|hb <;> rcases two _ hz with h|h <;> simp_all have pr := f.cross_projection ok bit l k cap a b ap bq have eq : (l ++ f.core bit ++ k).filter (fun z => decide (z=a ∨ z=b)) = _ := List.filter_eq_self.mpr (fun z hz => decide_eq_true (all z hz)) rw [eq,P455SlotProduct.profile_eq] at pr exact ⟨a,b,f.tag,bit,ab,by have := ok.1; omega,ok.2.1,pr⟩ theorem no_move_in_factor {r allow U V T} (capT : Cap r T) (two : BinaryNames T) (plainT : ¬ IsProfile r allow T) (factor : P455Quotient.Factor U T) : ¬ Move r allow noMark U V := by rintro mv obtain ⟨l,k,rfl⟩ := factor exact plainT (binary_move_profile (mv.extend_of_cap l k capT) two) theorem plain_good {r T U} (g : P455Quotient.Good (plain r) T U) : P455Quotient.Factor U T := by obtain ⟨v,p,h⟩ := g have eq : T=v := by induction p with | refl => rfl | snoc _ bad _ => exact False.elim bad exact eq ▸ h /-- No source cap is assumed. Liveness provides the cap in the actual binary component and forces all assigned representatives to be honest factors, including units. -/ theorem plain_equal {r allow T} (capT : Cap r T) (two : BinaryNames T) (plainT : ¬ IsProfile r allow T) (f : Frame Nat) (l k : W) (x y : Nat) (hp : f.p = [x]) (hq : f.q = [y]) (v : f.Valid r allow noMark) (val : Nat → P455Quotient.Q (plain r) T) : P455Quotient.eval (plain r) capT val (side f l k false) = P455Quotient.eval (plain r) capT val (side f l k true) := by classical let R := plain r let E := fun b => P455Quotient.eval R capT val (side f l k b) have one (b : Bool) (nz : E b ≠ P455Quotient.zero R T) : E b = E (!b) := by have rep (a) (h : a ∈ side f l k b) := P455Quotient.nonzero_representative R _ (P455Quotient.live_inputs R capT val _ nz a h) let h a := if m : a ∈ side f l k b then (rep a m).choose else [] have reps (a) (m : a ∈ side f l k b) : P455Quotient.ofWord R T (h a) = val a := by simpa only [h,dif_pos m] using (rep a m).choose_spec.2 have eq := P455Quotient.eval_rep R capT val _ h reps change P455Quotient.eval R capT val (side f l k b) ≠ _ at nz have good := (P455Quotient.nonzero_iff R).mp (eq ▸ nz) have cap := P455Quotient.good_cap R capT good rcases equal_or_move f l k b x y hp hq v h (mark := noMark) (fun _ _ _ _ => ⟨id,id⟩) cap with raw|move · change P455Quotient.eval R capT val _ = P455Quotient.eval R capT val _ rw [eq,raw,P455Quotient.eval_rep R capT val (side f l k (!b)) h (fun a m => reps a ((same_letters f l k b a).mpr m))] · exact False.elim (no_move_in_factor capT two plainT (plain_good good) move) by_cases zero : E false = P455Quotient.zero R T · by_cases z : E true = P455Quotient.zero R T · exact zero.trans z.symm · exact (one true z).symm · exact one false zero end P455BinaryEquality end /- Begin Problem455MarkedRank (from finite-semigroup-identity-bases). -/ section namespace P455MarkedRank open P455Witness P455SourceFamilies P455CrossedSupport P455SingletonEvaluation open P455SlotSaturation P455ActualGuards P455Uncrossed P455Compression P455FirstRewrite open P455FirstTesters P455SupportBound Problem455.Slots abbrev W := List Nat def model (r : Nat) (allow : Tag → Prop) (ts : Tiles) := combine (P455GuardProduct.product r allow ts) (P455EdgeProduct.product r allow ts) theorem eval_pair {A B : Type} (M : Model A) (N : Model B) (v : Nat → A × B) (w : W) : (combine M N).eval v w = (M.eval (fun a => (v a).1) w,N.eval (fun a => (v a).2) w) := by induction w with | nil => rfl | cons a w ih => change (_,_) = (_,_); rw [ih]; rfl theorem valid_pair {A B : Type} (M : Model A) (N : Model B) (u v : W) : (combine M N).Valid u v ↔ M.Valid u v ∧ N.Valid u v := by constructor · intro h; refine ⟨valid_left M N h,?_⟩ intro f have e := h (fun a => (M.unit,f a)) simpa only [eval_pair,Prod.mk.injEq] using (congrArg Prod.snd e) · rintro ⟨m,n⟩ val rw [eval_pair,eval_pair,m,n] theorem endpoint_feasible {r allow ts u w x y} (cap : P455Closure.Cap r u) (ident : (model r allow ts).Valid u w) (changed : select [x,y] u ≠ select [x,y] w) : ¬ EdgeViolation r allow ts u x y := by rintro ⟨e,s,match',read⟩ have obs := P455EdgeProduct.endpoint_observed cap ((valid_pair ..).mp ident).2 e read have diff := matched_change _ match' changed cases s · exact diff obs.1 · exact diff obs.2 theorem edge_eval {r allow ts} (v : Nat → P455EdgeProduct.Carrier r allow ts) (i : P455EdgeProduct.Index r allow ts) (w : W) : (P455EdgeProduct.product r allow ts).eval v w i = P455Quotient.eval i.R i.cap (fun a => v a i) w := by induction w with | nil => rfl | cons x _ ih => exact congrArg (P455Quotient.mul i.R i.cap (v x i)) ih theorem edge_coordinate {r allow ts} (i : P455EdgeProduct.Index r allow ts) : ∃ c : Certificate, MarksOnly (P455EdgeProduct.marks i.a i.b i.c i.d) c ∧ Holds r allow (P455EdgeProduct.marks i.a i.b i.c i.d) i.T (c.query r ts) := by obtain ⟨e,ea,eb,ec,ed,_,obs⟩ := i.test refine ⟨.edge e,?_,obs⟩ intro a b h rcases h with h|h · exact ⟨false,.inl ⟨ea.trans h.1.symm,eb.trans h.2.symm⟩⟩ · exact ⟨true,.inl ⟨ec.trans h.1.symm,ed.trans h.2.symm⟩⟩ def boundN := 2*(1+28)*geometric 28 6 def bound (r : Nat) := boundN + r*boundN + 1 theorem small_valid {r allow 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 : (P455GuardProduct.product r allow ts).Valid 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)) (feasible : ∀ b, ¬ EdgeViolation r allow ts (side f l k b) x y) : let keep := retained r allow noMark (side f l k false) x y (model r allow ts).Valid (small (side f l k false) keep) (small (side f l k true) keep) := by dsimp only apply (valid_pair ..).mpr constructor · intro val; funext i obtain ⟨c,only,test⟩ := P455LocalIdentity.guard_coordinate i rw [P455LocalIdentity.coordinate_eval,P455LocalIdentity.coordinate_eval] exact P455LocalIdentity.marked_equal i.cap ts c only test f l k x y hp hq fv capF u₀ w cap₀ identity flip₀ changed path cmp feasible _ · intro val; funext i obtain ⟨c,only,test⟩ := edge_coordinate i rw [edge_eval,edge_eval] exact P455LocalIdentity.marked_equal i.cap ts c only test f l k x y hp hq fv capF u₀ w cap₀ identity flip₀ changed path cmp feasible _ theorem bounded_step {r allow 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₀) (ident : (model r allow ts).Valid 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)) (feasible : ∀ b, ¬ EdgeViolation r allow ts (side f l k b) x y) : P455FirstRewrite.Step (fun a b => (model r allow ts).Valid a b ∧ rank a b ≤ bound r) (side f l k false) (side f l k true) := by have idG := ((valid_pair ..).mp ident).1 apply bounded_step_of_capacity (model r allow ts) (mark := noMark) f l k hp hq fv false capF · exact capacity cap₀ idG changed path flip₀ capF ⟨f,false,l,k,hp,hq,fv,rfl⟩ cmp · exact small_valid f l k x y hp hq fv capF u₀ w cap₀ idG flip₀ changed path cmp feasible end P455MarkedRank end /- Begin Problem455BinaryProduct (from finite-semigroup-identity-bases). -/ section /- Finite binary coordinates. Profile coordinates use their actual marked- move quotient with the empty set of marks. All other binary templates use the plain factor monoid. The unary power is included explicitly. -/ namespace P455BinaryProduct open P455Witness P455FirstRewrite P455FirstTesters P455BinaryEquality P455SlotSaturation open P455Uncrossed Problem455.Slots abbrev W := List Nat structure Index (r : Nat) (allow : Tag → Prop) where num : Fin (Problem455Finite.wordsUpTo [0,1] (2*r)).length prof : Bool cap : P455Closure.Cap r ((Problem455Finite.wordsUpTo [0,1] (2*r)).get num) ok : let T := (Problem455Finite.wordsUpTo [0,1] (2*r)).get num (T = power r ∨ (0 < T.count 0 ∧ 0 < T.count 1)) ∧ (prof = true ↔ IsProfile r allow T) def Index.T (i : Index r allow) := (Problem455Finite.wordsUpTo [0,1] (2*r)).get i.num def Index.R (i : Index r allow) := if i.prof then rules r allow noMark else plain r theorem Index.bound (i : Index r allow) : P455Quotient.Cap i.R.r i.T := by cases b : i.prof <;> simpa [Index.R,Index.T,b,plain,rules,Problem455Finite.rules,P455Quotient.Cap,P455Closure.Cap] using i.cap abbrev Carrier (r : Nat) (allow : Tag → Prop) := (i : Index r allow) → P455Quotient.Q i.R i.T def model (r : Nat) (allow : Tag → Prop) : Model (Carrier r allow) where op := fun x y i => P455Quotient.mul i.R i.bound (x i) (y i) unit := fun i => P455Quotient.ofWord i.R i.T [] assoc := fun x y z => funext (fun i => P455Quotient.mul_assoc i.R i.bound (x i) (y i) (z i)) oneL := fun x => funext (fun i => (P455Quotient.unit_laws i.R i.bound (x i)).1) oneR := fun x => funext (fun i => (P455Quotient.unit_laws i.R i.bound (x i)).2) theorem eval_at (i : Index r allow) (v : Nat → Carrier r allow) (w : W) : (model r allow).eval v w i = P455Quotient.eval i.R i.bound (fun x => v x i) w := by induction w with | nil => rfl | cons a w ih => exact congrArg (P455Quotient.mul i.R i.bound (v a i)) ih theorem empty_mark_eval {r allow T} (cap : P455Closure.Cap r T) (f : P455Closure.Frame Nat) (l k : W) (x y : Nat) (hp : f.p = [x]) (hq : f.q = [y]) (fv : f.Valid r allow noMark) (val : Nat → P455Quotient.Q (rules r allow noMark) T) : P455Quotient.eval (rules r allow noMark) cap val (side f l k false) = P455Quotient.eval (rules r allow noMark) cap val (side f l k true) := by apply Classical.byContradiction intro diff obtain ⟨b,_,⟨h,rep⟩,_⟩ := difference_live_representatives cap f l k val diff have eq := uncrossed_eval cap f l k b x y hp hq fv val h (fun a m => (rep a m).2) (fun _ _ _ _ => ⟨id,id⟩) cases b · exact diff eq · exact diff eq.symm theorem identity {r allow} (f : P455Closure.Frame Nat) (l k : W) (x y : Nat) (hp : f.p = [x]) (hq : f.q = [y]) (fv : f.Valid r allow noMark) : (model r allow).Valid (side f l k false) (side f l k true) := by intro val; funext i; rw [eval_at,eval_at] have names : BinaryNames i.T := by intro a ha; have h := P455GuardSubproduct.letters (List.get_mem _ i.num) a ha simpa using h let w := side f l k have coord (R : P455Quotient.Rules Nat) (cap : P455Quotient.Cap R.r i.T) (eq : R = i.R) (any : ∀ v : Nat → P455Quotient.Q R i.T, P455Quotient.eval R cap v (w false) = P455Quotient.eval R cap v (w true)) : P455Quotient.eval i.R i.bound (fun x => val x i) (w false) = P455Quotient.eval i.R i.bound (fun x => val x i) (w true) := by subst R; exact any _ cases bit : i.prof with | false => apply coord (plain r) i.cap (by simp [Index.R,bit]) exact plain_equal i.cap names (fun h => by have := i.ok.2.mpr h; simp_all) f l k x y hp hq fv | true => apply coord (rules r allow noMark) i.cap (by simp [Index.R,bit]) exact empty_mark_eval i.cap f l k x y hp hq fv end P455BinaryProduct end /- Begin Problem455FullSingleton (from finite-semigroup-identity-bases). -/ section namespace P455FullSingleton open P455Witness P455SourceFamilies P455CrossedSupport P455ActualGuards open P455MarkedRank P455Uncrossed P455Compression P455FirstRewrite open P455FirstTesters P455SlotSaturation P455SupportBound Problem455.Slots abbrev W := List Nat def model (r : Nat) (allow : Tag → Prop) (ts : Tiles) := combine (product r) (combine (P455MarkedRank.model r allow ts) (combine (P455BinaryProduct.model r allow) (P455StructuralProduct.product r allow))) private theorem short {r : Nat} (hr : 0 < r) (i : P455FirstTesters.Index r) : i.val.length < 2*r := by rcases i.property with p|b · rw [p,power,List.length_replicate]; omega · have count {w : W} (names : ∀ x ∈ w, x=0 ∨ x=1) : w.length = w.count 0 + w.count 1 := by induction w with | nil => rfl | cons x t ih => have tail := ih (fun a m => names a (List.mem_cons_of_mem _ m)) rcases names x List.mem_cons_self with h|h <;> simp [h,tail,List.count_cons] <;> omega have len := count b.1 have ac := b.2.1 0; have bc := b.2.1 1; have under := b.2.2.2.2 omega theorem primitive_identity {r allow} (f : P455Closure.Frame Nat) (l k : W) (x y : Nat) (hp : f.p = [x]) (hq : f.q = [y]) (fv : f.Valid r allow noMark) : (product r).Valid (side f l k false) (side f l k true) := by have hr : 0 < r := by have := fv.1; omega intro val; funext i have eq (w : W) : (product r).eval val w i = P455Quotient.eval (plain r) i.cap (fun x => val x i) w := by induction w with | nil => rfl | cons a w ih => exact congrArg (P455Quotient.mul (plain r) i.cap (val a i)) ih rw [eq,eq] have binary : P455BinaryEquality.BinaryNames i.val := by rcases i.property with e|b · intro a m; rw [e] at m; exact .inl (List.eq_of_mem_replicate m) · exact b.1 have notProf : ¬ P455BinaryEquality.IsProfile r allow i.val := by rintro ⟨a,b,t,bit,_,len,_,profileEq⟩ have lt := short hr i rw [profileEq,P455ProfileComponent.profile_length,len] at lt; omega exact P455BinaryEquality.plain_equal i.cap binary notProf f l k x y hp hq fv _ theorem guard_valid {r allow ts u v} (valid : (model r allow ts).Valid u v) : (P455GuardProduct.product r allow ts).Valid u v := ((valid_pair ..).mp (((valid_pair ..).mp ((valid_pair ..).mp valid).2).1)).1 theorem small_valid {r allow 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₀) (valid : (model r allow ts).Valid 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)) (feasible : ∀ b, ¬ EdgeViolation r allow ts (side f l k b) x y) : let keep := retained r allow noMark (side f l k false) x y (model r allow ts).Valid (small (side f l k false) keep) (small (side f l k true) keep) := by let u := side f l k false let keep := retained r allow noMark u x y obtain ⟨lt,cx,cy,_⟩ := flip_counts capF (show ClosedFlip r allow u x y from ⟨f,false,l,k,hp,hq,fv,rfl⟩) have hx : x ∈ keep := mem_retained.mpr ⟨List.count_pos_iff.mp (cx.symm ▸ (by omega : 0 < r)),.inl (.inl (P455Paths.near_self ..))⟩ have hy : y ∈ keep := mem_retained.mpr ⟨List.count_pos_iff.mp (cy.symm ▸ (by omega : 0 < r)),.inl (.inr (P455Paths.near_self ..))⟩ obtain ⟨g,L,K,gp,gq,gv,both,_⟩ := P455CompressedFrame.canonical_pair f l k keep hx hy hp hq fv false capF change (model r allow ts).Valid (small (side f l k false) keep) (small (side f l k true) keep) have mark := P455MarkedRank.small_valid f l k x y hp hq fv capF u₀ w cap₀ (guard_valid valid) flip₀ changed path cmp feasible refine (valid_pair ..).mpr ⟨?_,(valid_pair ..).mpr ⟨mark,(valid_pair ..).mpr ⟨?_,?_⟩⟩⟩ · rw [both,both]; exact primitive_identity g L K x y gp gq gv · rw [both,both]; exact P455BinaryProduct.identity g L K x y gp gq gv · rw [both,both]; exact P455StructuralProduct.identity g L K x y gp gq gv /-- The small identity is semantically proved in every coordinate above. Applying its common nonempty substitution is one ordinary semigroup deduction step on the actual source words. -/ theorem bounded_step {r allow 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₀) (ident : (model r allow ts).Valid 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)) (feasible : ∀ b, ¬ EdgeViolation r allow ts (side f l k b) x y) : P455FirstRewrite.Step (fun a b => (model r allow ts).Valid a b ∧ rank a b ≤ bound r) (side f l k false) (side f l k true) := by apply bounded_step_of_capacity (model r allow ts) (mark := noMark) f l k hp hq fv false capF · exact capacity cap₀ (guard_valid ident) changed path flip₀ capF ⟨f,false,l,k,hp,hq,fv,rfl⟩ cmp · exact small_valid f l k x y hp hq fv capF u₀ w cap₀ ident flip₀ changed path cmp feasible theorem no_basis_of_witnesses {r allow ts} (hr : 0 < r) (unbounded : ∀ k, ∃ U V D, RankWitness (model r allow ts) r U V D ∧ k < D.length) (basis : List (W × W)) (sound : ∀ u v, (u,v) ∈ basis → (model r allow ts).Valid u v) : ∃ U V, U ≠ [] ∧ V ≠ [] ∧ (model r allow ts).Valid U V ∧ ¬ Derives (fun u v => (u,v) ∈ basis) U V := first_change_no_finite_basis _ r hr unbounded basis sound end P455FullSingleton end /- Begin Problem455FiniteModel (from finite-semigroup-identity-bases). -/ section namespace P455FiniteModel open P455FirstRewrite def Covered (α : Type) := ∃ xs : List α, ∀ a, a ∈ xs theorem from_codes {α β : Type} (f : α → β) (inj : ∀ a b, f a=f b → a=b) (xs : List β) (all : ∀ a, f a∈xs) : Covered α := by classical let pick (b : β) := if h : ∃ a, f a=b then [Classical.choose h] else [] refine ⟨xs.flatMap pick,fun a => List.mem_flatMap.mpr ⟨f a,all a,?_⟩⟩ have h : ∃ z, f z=f a := ⟨a,rfl⟩ simp [pick,h,inj _ _ (Classical.choose_spec h)] theorem fin (n : Nat) : Covered (Fin n) := ⟨List.finRange n,fun a => by have h : a.val<(List.finRange n).length := by simp simpa using (List.getElem_mem (l := List.finRange n) h)⟩ theorem bool : Covered Bool := ⟨[false,true],fun b => by cases b <;> simp⟩ theorem sigma {ι : Type} {F : ι → Type} (base : Covered ι) (each : ∀ i, Covered (F i)) : Covered (Sigma F) := by obtain ⟨indices,all⟩ := base let vals (i) := Classical.choose (each i) refine ⟨indices.flatMap (fun i => (vals i).map (Sigma.mk i)),?_⟩ rintro ⟨i,x⟩ exact List.mem_flatMap.mpr ⟨i,all i,List.mem_map.mpr ⟨x,Classical.choose_spec (each i) x,rfl⟩⟩ theorem prod {α β : Type} (a : Covered α) (b : Covered β) : Covered (α×β) := by obtain ⟨xs,h⟩ := a; obtain ⟨ys,k⟩ := b exact ⟨xs.flatMap (fun x => ys.map (fun y => (x,y))),fun (x,y) => List.mem_flatMap.mpr ⟨x,h x,List.mem_map.mpr ⟨y,k y,rfl⟩⟩⟩ theorem pi {ι : Type} {F : ι → Type} (base : Covered ι) (each : ∀ i, Covered (F i)) (zero : ∀ i,F i) : Covered ((i : ι) → F i) := by classical obtain ⟨indices,all⟩ := base let set (f : (i : ι) → F i) (j : ι) (v : F j) := fun i : ι => if e : j=i then e ▸ v else f i have build (xs : List ι) : ∃ vs : List ((i : ι) → F i), ∀ f : (i : ι) → F i, ∃ g∈vs, ∀ i∈xs, g i=f i := by induction xs with | nil => exact ⟨[zero],fun _ => ⟨zero,by simp,by simp⟩⟩ | cons j xs ih => obtain ⟨gs,good⟩ := ih obtain ⟨ys,full⟩ := each j refine ⟨gs.flatMap (fun g => ys.map (set g j)),?_⟩ intro f obtain ⟨g,mg,match'⟩ := good f refine ⟨set g j (f j),List.mem_flatMap.mpr ⟨g,mg,List.mem_map_of_mem (full _)⟩,?_⟩ intro i mi by_cases e : j=i · subst i; simp [set] · simpa [set,e] using match' i ((List.mem_cons.mp mi).resolve_left (Ne.symm e)) obtain ⟨gs,h⟩ := build indices refine ⟨gs,?_⟩; intro f obtain ⟨g,mg,agree⟩ := h f exact (funext (fun i => agree i (all i))) ▸ mg theorem from_covered {α β : Type} (code : α → β) (inj : ∀ a b, code a=code b → a=b) (cov : Covered β) : Covered α := by obtain ⟨xs,h⟩ := cov exact from_codes code inj xs (fun _ => h _) private theorem coordinate {ι : Type} (inds : Covered ι) (rs : ι → P455Quotient.Rules Nat) (ts : ι → List Nat) : Covered ((i : ι) → P455Quotient.Q (rs i) (ts i)) := pi inds (fun i => ⟨_,Problem455Finite.carrier_complete (rs i) (ts i)⟩) (fun i => P455Quotient.zero (rs i) (ts i)) theorem primitive (r : Nat) : Covered (P455FirstTesters.Carrier r) := coordinate (from_codes Subtype.val (fun _ _ => Subtype.ext) _ P455FirstTesters.index_covered) _ _ theorem binary (r allow) : Covered (P455BinaryProduct.Carrier r allow) := by apply coordinate (from_covered (fun i : P455BinaryProduct.Index r allow => (i.num,i.prof)) _ (prod (fin _) bool)) intro i j; cases i; cases j; simp theorem structural (r allow) : Covered (P455StructuralProduct.Carrier r allow) := by apply coordinate (from_covered (fun i : P455StructuralProduct.Index r allow => i.pos) _ (fin _)) intro i j; cases i; cases j; simp private abbrev GCode (r : Nat) := (k : Bool) × (Fin (P455GuardProduct.words r k).length × Fin (P455GuardProduct.width k) × Fin (P455GuardProduct.width k)) theorem guard (r allow ts) : Covered (P455GuardProduct.Carrier r allow ts) := by let f (i : P455GuardProduct.Index r allow ts) : GCode r := ⟨i.kind,i.pos,i.a,i.b⟩ apply coordinate (from_covered f _ (sigma bool (fun _ => prod (fin _) (prod (fin _) (fin _))))) intro i j eq cases i with | mk k i a b cp ok => cases j with | mk m j c d cq oq => obtain km : k=m := congrArg Sigma.fst eq subst m have e : (i,a,b)=(j,c,d) := eq_of_heq (Sigma.mk.inj eq).2 simpa using e theorem edge (r allow ts) : Covered (P455EdgeProduct.Carrier r allow ts) := by apply coordinate (from_covered (fun i : P455EdgeProduct.Index r allow ts => (i.num,i.a,i.b,i.c,i.d)) _ (prod (fin _) (prod (fin _) (prod (fin _) (prod (fin _) (fin _)))))) intro i j; cases i; cases j; simp /-- An actual finite cover for the very type underlying the monoid used in both rank directions. No computability of a Prop-valued tile predicate is asserted by this classical cover. -/ theorem fixed_product (r allow ts) : Covered (P455FirstTesters.Carrier r × ((P455GuardProduct.Carrier r allow ts × P455EdgeProduct.Carrier r allow ts) × (P455BinaryProduct.Carrier r allow × P455StructuralProduct.Carrier r allow))) := prod (primitive r) (prod (prod (guard ..) (edge ..)) (prod (binary ..) (structural ..))) end P455FiniteModel end /- Begin Problem455PrefixValidity (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455FirstRewrite P455FirstTesters P455Quotient abbrev Word := List Nat def dropName (x : Nat) (u : Word) := u.filter (· != x) /-- In a live product of arbitrary representatives in a capped coordinate, an input occurring too often must represent the unit. -/ theorem overflow_unit {R : Rules Nat} {T : Word} (cap : Cap R.r T) (v : Nat → Q R T) (u : Word) (x : Nat) (many : R.r < u.count x) (live : eval R cap v u ≠ zero R T) : v x = ofWord R T [] := by classical have mem : x ∈ u := List.count_pos_iff.mp (by omega) have reps (z) (hz : z ∈ u) := nonzero_representative R (v z) (live_inputs R cap v u live z hz) let h : Nat → Word := fun z => if hz : z ∈ u then (reps z hz).choose else [] have rep (z) (hz : z ∈ u) : ofWord R T (h z) = v z := by simpa [h,hz] using (reps z hz).choose_spec.2 have g := (nonzero_iff R).mp ((eval_rep R cap v u h rep) ▸ live) have bounded := good_cap R cap g have empty : h x = [] := by cases e : h x with | nil => rfl | cons a t => have c : 1 ≤ (h x).count a := by rw [e]; simp have l := Nat.mul_le_mul_left (u.count x) c have split := P455DonorInterval.split_contributions h u x a have b := bounded a simp only [Nat.mul_one] at l omega simpa [empty] using (rep x mem).symm private theorem unit_drop {R : Rules Nat} {T : Word} (cap : Cap R.r T) (v : Nat → Q R T) (x : Nat) (unit : v x = ofWord R T []) (u : Word) : eval R cap v u = eval R cap v (dropName x u) := by induction u with | nil => rfl | cons a t ih => by_cases e : a = x · subst a; simpa [dropName,eval,unit,(unit_laws R cap _).1] using ih · simpa [dropName,eval,e] using congrArg (mul R cap (v a)) ih theorem overflow_coordinate {R : Rules Nat} {T : Word} (cap : Cap R.r T) (v : Nat → Q R T) {u w : Word} {x : Nat} (cu : R.r < u.count x) (cw : R.r < w.count x) (same : dropName x u = dropName x w) : eval R cap v u = eval R cap v w := by by_cases hu : v x = ofWord R T [] · rw [unit_drop cap v x hu u, unit_drop cap v x hu w,same] · have z (a : Word) (c : R.r < a.count x) : eval R cap v a = zero R T := Classical.byContradiction (fun nz => hu (overflow_unit cap v a x c nz)) rw [z u cu,z w cw] private theorem power_eval {r : Nat} (i : Index r) (v : Nat → Carrier r) (w : Word) : (product r).eval v w i = eval (plain r) i.cap (fun a => v a i) w := by induction w with | nil => rfl | cons a w ih => exact congrArg (mul (plain r) i.cap (v a i)) ih /-- The erasure identity holds in the actual fixed product including all marked and unmarked coordinates. All variable evaluations are arbitrary. -/ theorem overflow_valid {r allow ts} {u w : Word} {x : Nat} (cu : r < u.count x) (cw : r < w.count x) (same : dropName x u = dropName x w) : (P455FullSingleton.model r allow ts).Valid u w := by apply (P455MarkedRank.valid_pair ..).mpr refine ⟨?_,(P455MarkedRank.valid_pair ..).mpr ⟨(P455MarkedRank.valid_pair ..).mpr ⟨?_,?_⟩, (P455MarkedRank.valid_pair ..).mpr ⟨?_,?_⟩⟩⟩ · intro v; funext i; rw [power_eval,power_eval] exact overflow_coordinate i.cap _ cu cw same · intro v; funext i; rw [P455LocalIdentity.coordinate_eval,P455LocalIdentity.coordinate_eval] exact overflow_coordinate (R := i.R) (T := i.T) i.cap _ cu cw same · intro v; funext i; rw [P455MarkedRank.edge_eval,P455MarkedRank.edge_eval] exact overflow_coordinate (R := i.R) (T := i.T) i.cap _ cu cw same · intro v; funext i; rw [P455BinaryProduct.eval_at,P455BinaryProduct.eval_at] have capr : i.R.r = r := by cases h : i.prof <;> simp [P455BinaryProduct.Index.R,h,plain,P455Witness.rules,Problem455Finite.rules] exact overflow_coordinate i.bound _ (by simpa [capr] using cu) (by simpa [capr] using cw) same · intro v; funext i; rw [P455StructuralProduct.coordinate,P455StructuralProduct.coordinate] exact overflow_coordinate (R := plain r) (T := i.T) i.cap _ cu cw same end P455Prefix end /- Begin Problem455ReductionBoundary (from finite-semigroup-identity-bases). -/ section /- These two conditional implications use the very same tester product. The geometric data required to apply them are exhibited in the types. -/ namespace P455ReductionBoundary open P455Witness P455FirstRewrite P455CrossedSupport P455SourceFamilies P455SlotSaturation open P455ActualGuards P455Uncrossed P455FullSingleton P455Schedule Problem455.Slots abbrev W := List Nat theorem sym_step {G : W → W → Prop} {u v} (st : Step G u v) : Step G v u := by obtain ⟨a,b,l,k,h,rule,an,bn,hn,lo,hi⟩ := st exact ⟨b,a,l,k,h,rule.symm,bn,an,hn,hi,lo⟩ /-- Data on a scheduled local change. Independent intermediate words need no assumed algebraic validity. The changed pair and path refer back to the original endpoint identity U,V. -/ structure Layout (r : Nat) (allow : Tag → Prop) (ts : Tiles) (U V A B : W) where x : Nat y : Nat f : P455Closure.Frame Nat l : W k : W bit : Bool hp : f.p = [x] hq : f.q = [y] frame : f.Valid r allow noMark cap : P455Closure.Cap r (side f l k false) anchor : ClosedFlip r allow U x y changed : select [x,y] U ≠ select [x,y] V path : P455Quotient.Walk (P455Closure.Move r allow noMark) U (side f l k bit) compressed : Compressed r (side f l k bit) legal : ∀ b, ¬ EdgeViolation r allow ts (side f l k b) x y fromWord : A = side f l k bit toWord : B = side f l k (!bit) theorem Layout.step {r allow ts U V A B} (g : Layout r allow ts U V A B) (capU : P455Closure.Cap r U) (idUV : (model r allow ts).Valid U V) : Step (fun a b => (model r allow ts).Valid a b ∧ rank a b ≤ P455MarkedRank.bound r) A B := by have mv : P455Closure.Move r allow noMark (side g.f g.l g.k false) (side g.f g.l g.k true) := ⟨g.f,false,g.l,g.k,g.frame,rfl,rfl,g.cap⟩ have path0 : P455Quotient.Walk (P455Closure.Move r allow noMark) U (side g.f g.l g.k false) := by cases h : g.bit · simpa [h] using g.path · exact .snoc (by simpa [h] using g.path) mv.symm have cmp0 : Compressed r (side g.f g.l g.k false) := by cases h : g.bit · simpa [h] using g.compressed · have cmp := g.compressed; rw [h] at cmp exact fun a b link => cmp a b ((Problem455BlockBridge.move_link mv a b).mp link) have st := bounded_step g.f g.l g.k g.x g.y g.hp g.hq g.frame g.cap U V capU idUV g.anchor g.changed path0 cmp0 g.legal have transport {a b c d : W} {G : W → W → Prop} (h : a=c) (j : b=d) (s : Step G c d) : Step G a b := by subst c; subst d; exact s apply transport g.fromWord g.toWord cases g.bit · exact st · exact sym_step st theorem scheduled_deduction {r allow ts C E} (acy : Acyclic C E) (A B : Bits) (start : Good C E A) (finish : Good C E B) (fixed : ∀ a, A a ≠ B a → a ∈ C) (word : Bits → W) (cap : P455Closure.Cap r (word A)) (valid : (model r allow ts).Valid (word A) (word B)) (geometry : ∀ s t, Toward C E B s t → Nonempty (Layout r allow ts (word A) (word B) (word s) (word t))) : Derives (fun a b => (model r allow ts).Valid a b ∧ rank a b ≤ P455MarkedRank.bound r) (word A) (word B) := derivation acy A B start finish fixed word _ (fun s t move => (geometry s t move).elim (fun g => g.step cap valid)) /-- The size parameter is inside the quantifier for one fixed monoid. The profile-geometry and semantic inputs are explicit, especially the constant identity and the complete class of the all-zero word. -/ theorem rectangle_family_no_basis {r allow ts} (hr : 0 < r) (padding : ∀ k : Nat, ∃ (t : Nat) (middle tail : W), k < 2*t ∧ (∀ x ∈ middle ++ tail, x < 2*t) ∧ P455Quotient.Cap r (P455RectangleRank.word t middle tail (P455RectangleRank.constant false)) ∧ (model r allow ts).Valid (P455RectangleRank.word t middle tail (P455RectangleRank.constant false)) (P455RectangleRank.word t middle tail (P455RectangleRank.constant true)) ∧ (∀ w, (model r allow ts).Valid (P455RectangleRank.word t middle tail (P455RectangleRank.constant false)) w → ∃ b, w = P455RectangleRank.word t middle tail b) ∧ (∀ b, (model r allow ts).Valid (P455RectangleRank.word t middle tail (P455RectangleRank.constant false)) (P455RectangleRank.word t middle tail b) → (∀ i, i+1 < t → b i = true → b (i+1) = true) ∧ (0 < t → b (t-1) = true → b 0 = true))) (basis : List (W × W)) (sound : ∀ u v, (u,v) ∈ basis → (model r allow ts).Valid u v) : ∃ U V, U ≠ [] ∧ V ≠ [] ∧ (model r allow ts).Valid U V ∧ ¬ Derives (fun u v => (u,v) ∈ basis) U V := by apply no_basis_of_witnesses hr _ basis sound intro k obtain ⟨t,m,z,big,letters,cap,eq,all,edges⟩ := padding k exact ⟨_,_,_,P455RectangleRank.witness hr (by omega) m z letters cap eq all edges,by simpa using big⟩ end P455ReductionBoundary end /- Begin Problem455StructuralReflection (from finite-semigroup-identity-bases). -/ section namespace P455StructuralReflection open P455Structural P455Witness P455SourceFamilies P455DefectRename P455SlotProduct open P455FirstTesters P455FirstRewrite P455Quotient Problem455.Slots Problem455Swap private theorem map_edge {r allow w a b} (f : Nat → Nat) (inj : Injects f) (edge : Edge w r allow a b) : Edge (w.map f) r allow (f a) (f b) := by rcases edge with ⟨tag,recProof⟩|⟨tag,recProof⟩ · exact .inl ⟨tag,rename_record f inj recProof⟩ · exact .inr ⟨tag,rename_record f inj recProof⟩ theorem rename_test {r allow w} (f : Nat → Nat) (inj : Injects f) (test : Structural w r allow) : Structural (w.map f) r allow := by have width {k} (ww : Width k w) : Width k (w.map f) := by obtain ⟨c,len,covers⟩ := ww refine ⟨c.map f,by simpa using len,?_⟩ intro a m obtain ⟨b,mb,rfl⟩ := List.mem_map.mp m exact List.mem_map_of_mem (covers b mb) rcases test with ⟨ww,o,p,q,op,oq,pq,ep,eq⟩|⟨ww,o,p,z,j,op,zo,zp,⟨tag,recProof⟩,see⟩ · exact .inl ⟨width ww,f o,f p,f q,fun h => op (inj h),fun h => oq (inj h), fun h => pq (inj h),map_edge f inj ep,map_edge f inj eq⟩ · exact .inr ⟨width ww,f o,f p,f z,j,fun h => op (inj h),fun h => zo (inj h), fun h => zp (inj h),⟨tag,rename_record f inj recProof⟩,rename_sees f inj see⟩ private theorem bigram_map (f : Nat → Nat) (inj : Injects f) (x y : Nat) (w : List Nat) : bigram (f x) (f y) (w.map f)=bigram x y w := by induction w with | nil => rfl | cons a t ih => cases t with | nil => simp [bigram,hit] | cons b t => change hit _ _ (some (f a)) (some (f b)) + _ = hit _ _ (some a) (some b) + _ have left : f a=f x ↔ a=x := ⟨fun e => inj e,congrArg f⟩ have right : f b=f y ↔ b=y := ⟨fun e => inj e,congrArg f⟩ simp only [hit,Option.some.injEq,left,right,← ih,List.map_cons] theorem rename_compressed {r w} (hr : 0 kept mem) have cp : P455Closure.Cap r T := eq ▸ cap_rename _ (extend_inj keep) (P455DefectProjection.select_cap keep cap) have st : Structural T r allow := eq ▸ rename_test _ (extend_inj keep) test have nc : Compressed r T := eq ▸ rename_compressed hr _ (extend_inj keep) cmp have low (x) (mem : x∈T) : x<4 := by obtain ⟨a,ha,rfl⟩ := List.mem_map.mp mem exact Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (kept ha)) width have found := Problem455Finite.covered (List.range 4) (4*r) T (capped_length 4 T cp low) (fun x mem => List.mem_range.mpr (low x mem)) obtain ⟨idx,pos⟩ := List.get_of_mem found let i : P455StructuralProduct.Index r allow := ⟨idx,pos.symm ▸ cp,pos.symm ▸ nc,pos.symm ▸ st⟩ have iden := ((P455MarkedRank.valid_pair ..).mp (((P455MarkedRank.valid_pair ..).mp ((P455MarkedRank.valid_pair ..).mp ident).2).2)).2 let vname (a : Nat) (j : P455StructuralProduct.Index r allow) := ofWord (plain r) j.T (image keep a) have observed := congrFun (iden vname) i rw [P455StructuralProduct.coordinate,P455StructuralProduct.coordinate] at observed have product (w : List Nat) : eval (plain r) i.cap (fun a => vname a i) w = ofWord (plain r) i.T ((select keep w).map keep.idxOf) := (eval_rep _ _ _ _ (image keep) (fun _ _ => rfl)).trans (congrArg _ (image_word keep w)) rw [product,product] at observed have sameT : i.T=T := pos rw [sameT] at observed have live : Good (plain r) T T := ⟨T,.refl _,[],[],by simp⟩ have walk := ((same_nonzero_class _ live).mp observed).2 have identical := walk.transport (P := fun w => T=w) rfl (fun bad _ => False.elim bad) exact (decode_map (fun _ mem => kept mem)).symm.trans ((congrArg (List.map (decode keep)) identical).trans (decode_map (fun _ mem => kept mem))) end P455StructuralReflection end /- Begin Problem455EnumBasic (from finite-semigroup-identity-bases). -/ section namespace P455Enum open P455PaddedTiles P455Witness Problem455.Slots structure Cover (α : Type) where list : List α mem : ∀ x, x ∈ list def Cover.map (s : Cover α) (f : α → β) (sur : ∀ y, ∃ x, f x=y) : Cover β := ⟨s.list.map f,fun y => let ⟨x,e⟩ := sur y; List.mem_map.mpr ⟨x,s.mem x,e⟩⟩ def Cover.bind (s : Cover α) (f : α → Cover β) (g : α → β → γ) (sur : ∀ y, ∃ a b, g a b=y) : Cover γ := ⟨s.list.flatMap fun a => (f a).list.map (g a),fun y => by obtain ⟨a,b,e⟩ := sur y exact List.mem_flatMap.mpr ⟨a,s.mem a,List.mem_map.mpr ⟨b,(f a).mem b,e⟩⟩⟩ def selectSub (xs : List α) (p : α → Prop) [DecidablePred p] := (xs.filter p).attach.map (fun t => (⟨t.val,by simpa using (List.mem_filter.mp t.property).2⟩ : Subtype p)) theorem selectSub_full {xs : List α} {p : α → Prop} [DecidablePred p] (x : Subtype p) (m : x.val ∈ xs) : x ∈ selectSub xs p := by have yes : x.val ∈ xs.filter p := List.mem_filter.mpr ⟨m,decide_eq_true x.property⟩ unfold selectSub apply List.mem_map.mpr exact ⟨⟨x.val,yes⟩,List.mem_attach ..,Subtype.ext rfl⟩ def bools : Cover Bool := ⟨[false,true],fun b=>by cases b <;> simp⟩ def fins (n : Nat) : Cover (Fin n) := ⟨List.finRange n,fun a => by have h : a.val < (List.finRange n).length := by simp simpa using List.getElem_mem (l := List.finRange n) h⟩ def options (s : Cover α) : Cover (Option α) := ⟨none::s.list.map some,fun x=>by cases x with | none => simp | some a => exact List.mem_cons_of_mem _ (List.mem_map_of_mem (s.mem a))⟩ def tiles (n : Nat) : Cover (Tile n) := let bs := bools.list let plain := (fins n).list let opt := (options (fins n)).list ⟨(bs.flatMap fun a => (bs.flatMap fun b => (bs.flatMap fun c => (bs.flatMap fun d => (bs.flatMap fun e => (bs.flatMap fun f => (opt.flatMap fun l => (plain.flatMap fun v => (opt.flatMap fun r => (plain.map fun z => ⟨a,b,c,d,e,f,l,v,r,z⟩)))))))))), by intro p cases p with | mk a b c d e f l v r z => simp only [List.mem_flatMap,List.mem_map] exact ⟨a,bools.mem _,b,bools.mem _,c,bools.mem _,d,bools.mem _,e,bools.mem _,f,bools.mem _, l,(options (fins n)).mem _,v,(fins n).mem _,r,(options (fins n)).mem _,z,(fins n).mem _,rfl⟩⟩ def search (s : List α) (p : α → Prop) [DecidablePred p] (bound : ∀ x, p x → x∈s) : Decidable (∃ x,p x) := decidable_of_iff (∃ x∈s,p x) ⟨fun ⟨x,_,h⟩ => ⟨x,h⟩,fun ⟨x,h⟩ => ⟨x,bound x h,h⟩⟩ def Cover.existsD (s : Cover α) (p : α → Prop) [DecidablePred p] : Decidable (∃ x,p x) := search s.list p (fun x _ => s.mem x) instance admittedD (M : MachineTable n) (p : Tile n) : Decidable (Admitted M p) := by unfold Admitted; infer_instance def tags (M : MachineTable n) := ((tiles n).list.filter (Admitted M)).map code theorem mem_tags {M : MachineTable n} {tag} : tag∈tags M ↔ allowed M tag := by simp only [tags,List.mem_map,List.mem_filter,decide_eq_true_eq] exact ⟨fun ⟨p,⟨_,h⟩,e⟩=>⟨p,e,h⟩,fun ⟨p,e,h⟩=>⟨p,⟨(tiles n).mem p,h⟩,e⟩⟩ instance allowedD (M : MachineTable n) (t) : Decidable (allowed M t) := decidable_of_iff _ mem_tags instance horizontalD (n : Nat) (s t) : Decidable ((system n).horizontal s t) := by unfold system Horizontal exact @Cover.existsD _ (tiles n) _ (fun p => @Cover.existsD _ (tiles n) _ (fun q => inferInstance)) instance verticalD (n : Nat) (s t) : Decidable ((system n).vertical s t) := by unfold system Vertical exact @Cover.existsD _ (tiles n) _ (fun p => @Cover.existsD _ (tiles n) _ (fun q => inferInstance)) def capD (r : Nat) (w : List Nat) : Decidable (P455Closure.Cap r w) := decidable_of_iff (∀ x∈w,w.count x≤r) ⟨fun h x => by by_cases m : x∈w · exact h x m · simp [List.count_eq_zero.mpr m],fun h x _ => h x⟩ def primitive (r : Nat) : Cover (P455FirstTesters.Index r) := let xs := Problem455Finite.wordsUpTo [0,1] (2*r) letI : DecidablePred (fun w : List Nat => w=P455FirstTesters.power r ∨ P455FirstTesters.Binary r w) := fun w => by letI : Decidable (P455Quotient.Cap r w) := capD r w unfold P455FirstTesters.Binary infer_instance ⟨selectSub xs _,fun i => selectSub_full i (P455FirstTesters.index_covered i)⟩ end P455Enum end /- Begin Problem455PrefixNormalize (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455FirstRewrite P455Compression P455Quotient def gather (r x : Nat) (u : Word) := List.replicate (r+1) x ++ dropName x u def Steps (r : Nat) (allow : P455Witness.Tag → Prop) (ts : P455Witness.Tiles) (u v : Word) := (P455FullSingleton.model r allow ts).Valid u v ∧ rank u v ≤ 2*(r+2)+1 @[simp] theorem drop_mem (a x : Nat) (u : Word) : a ∈ dropName x u ↔ a ∈ u ∧ a ≠ x := by simp [dropName] @[simp] theorem drop_count (a x : Nat) (u : Word) : (dropName x u).count a = if a = x then 0 else u.count a := by by_cases h : a = x · rw [if_pos h]; exact List.count_eq_zero.mpr (fun m => ((drop_mem ..).mp m).2 h) · simp [dropName,List.count_filter,h] @[simp] theorem gather_drop (r x : Nat) (u : Word) : dropName x (gather r x u) = dropName x u := by simp [gather,dropName,List.filter_append,List.filter_filter] @[simp] theorem gather_count (r x : Nat) (u : Word) : (gather r x u).count x = r+1 := by simp [gather] private theorem code_len (n : Nat) (cs : List Piece) : (code n cs).length = cs.length := by induction cs generalizing n with | nil => rfl | cons p cs ih => cases p <;> simp [code,ih] private theorem compact_length (x : Nat) : ∀ cs : List Piece, noTouch cs → (∀ p ∈ cs, good [x] p) → cs.length ≤ 2*(cs.flatMap body).count x+1 | [],_,_ => by simp | .literal b :: cs,ok,g => by have bx : b = x := List.mem_singleton.mp (g _ List.mem_cons_self) have tail := compact_length x cs ok (fun p h => g _ (List.mem_cons_of_mem _ h)) subst b simp [body,List.count_cons]; omega | [.gap a],_,_ => by simp [body] | .gap a :: .literal b :: cs,ok,g => by have bx : b = x := List.mem_singleton.mp (g (.literal b) (by simp)) have tail := compact_length x cs ok (fun p h => g _ (by simp [h])) subst b simp [body,List.count_cons]; omega | .gap _ :: .gap _ :: _,ok,_ => False.elim ok private theorem small_len (u : Word) (x : Nat) : (small u [x]).length ≤ 2*u.count x+1 := by have h := compact_length x (pieces [x] u) (maximal [x] u) (pieces_good [x] u) rw [decoded] at h simpa only [small,code_len] using h private theorem expand_drop {s : Word} {e : Nat → Word} {x : Nat} (exp : P455Retained.Expansion s e (fun a => a ∈ [x])) : ∀ (t : Word), (∀ a ∈ t, a ∈ s) → (dropName x t).flatMap e = dropName x (t.flatMap e) := by intro t sub induction t with | nil => rfl | cons a t ih => have inc (b) (h : b ∈ t) := sub b (List.mem_cons_of_mem _ h) have eq := ih inc have m := sub a List.mem_cons_self by_cases same : a = x · subst a simpa [dropName,List.filter_append,exp.literal x m (by simp)] using eq · have gap := exp.gaps a m (by simpa using same) have all : (e a).filter (· != x) = e a := List.filter_eq_self.mpr (fun b hb => by simpa using gap.2.2 b hb) simpa [dropName,List.filter_append,same,all] using congrArg (List.append (e a)) eq private theorem map_reps (k x : Nat) (e : Nat → Word) (fixed : e x = [x]) : (List.replicate k x).flatMap e = List.replicate k x := by induction k with | zero => rfl | succ k ih => simp [List.replicate_succ,fixed,ih] /-- If at most r+2 copies are present, the entire collection and truncation of this name takes a single rule instance with at most 2(r+2)+1 names, regardless of the length or multiplicities of the intervening gaps. -/ theorem gather_step {r allow ts x} (u : Word) (lo : r < u.count x) (hi : u.count x ≤ r+2) : Step (Steps r allow ts) u (gather r x u) := by let s := small u [x] let e := expand u [x] have cnt : s.count x = u.count x := counts_retained u [x] x (by simp) have xs : x ∈ s := List.count_pos_iff.mp (by omega) have expanded : s.flatMap e = u := recover u [x] have exp := canonical u [x] have fixed : e x = [x] := exp.literal x xs (by simp) have right : (gather r x s).flatMap e = gather r x u := by rw [gather,List.flatMap_append,map_reps _ _ _ fixed, expand_drop exp s (fun _ m => m),expanded] rfl have covers (a : Nat) (h : a ∈ gather r x s) : a ∈ s := by rcases List.mem_append.mp h with h|h · exact (List.eq_of_mem_replicate h) ▸ xs · exact ((drop_mem ..).mp h).1 have rankBound : rank s (gather r x s) ≤ s.length := by apply size_le (names_distinct _) intro a ha exact (List.mem_append.mp ((mem_names ..).mp ha)).elim id (covers a) have short := small_len u x change s.length ≤ _ at short have valid := overflow_valid (allow := allow) (ts := ts) (x := x) (u := s) (w := gather r x s) (by omega : r < s.count x) (by simp) (gather_drop r x s).symm refine ⟨s,gather r x s,[],[],e,.inl ⟨valid,by omega⟩,fun h => ?_,?_, P455SmallRank.expansion_nonempty u [x],by simpa using expanded.symm,by simpa using right.symm⟩ · simp [h] at xs · simp [gather,List.replicate_succ] theorem context_step {G : Word → Word → Prop} {u v : Word} (p q : Word) (s : Step G u v) : Step G (p ++ u ++ q) (p ++ v ++ q) := by obtain ⟨a,b,l,t,h,rule,an,bn,hn,rfl,rfl⟩ := s exact ⟨a,b,p++l,t++q,h,rule,an,bn,hn,by simp [List.append_assoc],by simp [List.append_assoc]⟩ theorem context_derives {G : Word → Word → Prop} {u v : Word} (p q : Word) (s : Derives G u v) : Derives G (p ++ u ++ q) (p ++ v ++ q) := by induction s with | refl => exact .refl _ | snoc _ step ih => exact .snoc ih (context_step p q step) /-- All high multiplicities, including arbitrarily large ones. -/ theorem gather_deduction {r allow ts x} (u : Word) (sat : r < u.count x) : Derives (Steps r allow ts) u (gather r x u) := by induction u with | nil => simp at sat | cons a t ih => by_cases tail : r < t.count x · have path := context_derives [a] [] (ih tail) have low : r < (a :: gather r x t).count x := by simp [List.count_cons]; omega have high : (a :: gather r x t).count x ≤ r+2 := by simp [List.count_cons]; split <;> omega have step := gather_step (allow := allow) (ts := ts) _ low high have eq : gather r x (a::gather r x t) = gather r x (a::t) := by by_cases same : a=x <;> simp [gather,dropName,List.filter_append,List.filter_filter,same] exact (show Derives (Steps r allow ts) (a::t) (a::gather r x t) by simpa using path).snoc (eq ▸ step) · have high : (a :: t).count x ≤ r+2 := by simp only [List.count_cons]; split <;> omega exact .snoc (.refl _) (gather_step _ sat high) end P455Prefix end /- Begin Problem455ConstantProduct (from finite-semigroup-identity-bases). -/ section /- The checked geometric constant-layout implication at the same monoid as the finite-basis rank bounds. The mixed bit assignments need no assumption of validity, goodness, or membership in a two-word class. -/ namespace P455ConstantProduct open P455Witness P455FirstRewrite P455Uncrossed P455FirstTesters P455MarkedRank open P455ConstantLayout abbrev W := List Nat private theorem ordinary_chain {A : Type} (M : Model A) {r allow used U V} (each : ∀ (f : P455Closure.Frame Nat) (l k : W) (x y : Nat), f.p=[x] → f.q=[y] → f.Valid r allow (fun _ _ => False) → M.Valid (side f l k false) (side f l k true)) (p : Chain r allow used U V) : M.Valid U V := by induction p with | refl => intro _; rfl | snoc _ flip ih => obtain ⟨x,y,f,b,l,k,_,hp,hq,valid,rfl,rfl⟩ := flip intro val have eq := each f l k x y hp hq valid val cases b · exact (ih val).trans eq · exact (ih val).trans eq.symm theorem identity {r allow ts} (endWord : Bool → W) (layout : Layout r allow ts endWord) : (P455FullSingleton.model r allow ts).Valid (endWord false) (endWord true) := by refine (valid_pair ..).mpr ⟨ordinary_chain _ P455FullSingleton.primitive_identity layout.path, (valid_pair ..).mpr ⟨(valid_pair ..).mpr ⟨?_,?_⟩, (valid_pair ..).mpr ⟨ordinary_chain _ P455BinaryProduct.identity layout.path, ordinary_chain _ P455StructuralProduct.identity layout.path⟩⟩⟩ · intro val; funext i obtain ⟨c,only,obs⟩ := P455LocalIdentity.guard_coordinate i rw [P455LocalIdentity.coordinate_eval,P455LocalIdentity.coordinate_eval] exact marked_equal i.cap endWord layout c only obs _ · intro val; funext i obtain ⟨c,only,obs⟩ := edge_coordinate i rw [edge_eval,edge_eval]; exact marked_equal i.cap endWord layout c only obs _ theorem rectangle_no_basis {r allow ts} (hr : 0 < r) (padding : ∀ k : Nat, ∃ (t : Nat) (middle tail : W), k < 2*t ∧ (∀ x ∈ middle ++ tail, x < 2*t) ∧ Nonempty (Layout r allow ts (fun b => P455RectangleRank.word t middle tail (P455RectangleRank.constant b))) ∧ (∀ w, (P455FullSingleton.model r allow ts).Valid (P455RectangleRank.word t middle tail (P455RectangleRank.constant false)) w → ∃ b, w = P455RectangleRank.word t middle tail b) ∧ (∀ b, (P455FullSingleton.model r allow ts).Valid (P455RectangleRank.word t middle tail (P455RectangleRank.constant false)) (P455RectangleRank.word t middle tail b) → (∀ i, i+1 (u,v) ∈ basis) U V := by apply P455ReductionBoundary.rectangle_family_no_basis hr _ basis sound intro k obtain ⟨t,m,z,large,bounded,⟨layout⟩,represent,edges⟩ := padding k have cap : P455Quotient.Cap r (P455RectangleRank.word t m z (P455RectangleRank.constant false)) := by intro a; by_cases mem : a ∈ P455RectangleRank.word t m z (P455RectangleRank.constant false) · exact Nat.le_of_eq (layout.uniform false a mem) · simp [List.count_eq_zero.mpr mem] exact ⟨t,m,z,large,bounded,cap,identity _ layout,represent,edges⟩ end P455ConstantProduct end /- Begin Problem455GraphReduction (from finite-semigroup-identity-bases). -/ section namespace P455GraphReduction open P455GridAssembly P455GridRows P455Witness P455Schedule P455FirstRewrite def WordEdge (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : List Nat) (ts : Tiles) (nodes : Nat → Node) : Edges := fun a b => ∃ e : EdgeCertificate, e.a=nodes a ∧ e.b=nodes b ∧ Arrow r allow mark w ts e private theorem path_list {R : Edges} {a b} (p : Path R a b) : ∃ (n : Nat) (v : Nat → Nat), 0 exact ⟨1,fun i => if i=0 then a else b,by decide,by simp,by simp,by intro i lt have eq : i=0 := by omega simpa [eq] using ed⟩ | @join a b c _ _ left right => obtain ⟨n,v,np,v0,vn,vs⟩ := left obtain ⟨m,q,mp,q0,qm,qs⟩ := right let f (i : Nat) := if i (P455FullSingleton.model r allow ts).Valid u v ∧ rank u v ≤ P455MarkedRank.bound r) (word A) (word B) ∨ Nonempty (Rectangle allow ts) := by classical by_cases existsLoop : ∃ a, Path (induced C (WordEdge r allow P455SlotSaturation.noMark w ts nodes)) a a · obtain ⟨a,loop⟩ := existsLoop exact .inr (rectangle_of_cycle law nodes C funct loop) · exact .inl (P455ReductionBoundary.scheduled_deduction (fun a p => existsLoop ⟨a,p⟩) A B start finish fixed word cap valid localChange) end P455GraphReduction end /- Begin Problem455EnumQueries (from finite-semigroup-identity-bases). -/ section namespace P455Enum open P455Witness Problem455.Slots Problem455Swap theorem linkNames {r a b} {w : List Nat} (hr : 0 decide (Joined (Link r w) x a)) have mem {a} : a∈s ↔ a∈vertices ∧ Joined (Link r w) x a := by simp [s] have ins : s∈subsets := Problem455Finite.covered _ _ _ (List.length_filter_le ..) (fun a m => (mem.mp m).1) have st : stable r w s := fun a ma b mb ed => mem.mpr ⟨List.mem_cons_of_mem _ mb,.extend (mem.mp ma).2 ed⟩ exact (mem.mp (closed s ins (mem.mpr ⟨List.mem_cons_self,.refl _⟩) st)).2 · intro path s _ start st induction path with | refl => exact start | extend p ed ih => exact st _ ih _ (ed.elim (fun h => (linkNames hr h).2) (fun h => (linkNames hr h).1)) ed) def blockD {r} (hr : 0 seesD ..) (fun j h => List.mem_map.mpr ⟨(a,j),h.subset (by simp),rfl⟩) instance typedD (w a b tag) : Decidable (typed w a b tag) := by unfold typed; infer_instance /-- Only static propositions require a certificate-specific decision procedure. -/ def Stat : Query → Type | .fixed p => Decidable p | .both a b | .either a b => Stat a × Stat b | _ => Unit def holdsD {r} (hr : 0 s | .count ..,_ | .deficient ..,_ | .record ..,_ | .markedBit ..,_ | .order ..,_ | .slot ..,_ => by unfold Holds; infer_instance | .separate a b,_ => by letI := blockD hr w a b; unfold Holds; infer_instance | .both a b,s | .either a b,s => by letI := holdsD hr allow mark w a s.1 letI := holdsD hr allow mark w b s.2 unfold Holds infer_instance def statAll {qs : List Query} (f : ∀ q∈qs, Stat q) : Stat (allQ qs) := match qs with | [] => isTrue trivial | q::_ => (f q List.mem_cons_self,statAll (fun a m => f a (List.mem_cons_of_mem _ m))) def statMap {α} {xs : List α} (f : α→Query) (g : ∀ x, Stat (f x)) : Stat (allQ (xs.map f)) := match xs with | [] => isTrue trivial | x::xs => (g x,@statMap _ xs f g) def statAppend (xs ys : List Query) (h : Stat (allQ xs)) (k : Stat (allQ ys)) : Stat (allQ (xs++ys)) := match xs with | [] => k | _::xs => (h.1,statAppend xs ys h.2 k) def statEarly (xs ys : List Nat) : Stat (earlyBefore xs ys) := match xs with | [] => isTrue trivial | x::xs => statAppend _ _ (statMap (fun y=>earlier x 2 y 0) (xs:=ys) (fun _=>())) (statEarly xs ys) def statContact (r a b) (c : ContactChoice) : Stat (contact r a b c) := by cases c with | record t rev => cases rev <;> exact () | port p rev => exact (inferInstanceAs (Decidable _),(),(),(statEarly _ _,statEarly _ _),(),isTrue trivial) def statDiff (xs : List Nat) : Stat (differentBlocks xs) := match xs with | [] => isTrue trivial | _::xs => (statMap _ (fun _=>()),statDiff xs) def statTerminal (r o i) (d : SlotDefect) : Stat (terminalSlot r o i d) := by cases d with | deficient a => exact ((),()) | overflow xs => exact (inferInstanceAs (Decidable _),statDiff _,statMap _ (fun _=>((),())),isTrue trivial) def statRoute (r o : Nat) (xs : List (Nat × ContactChoice)) (f : Nat→Query) (sf : ∀ i, Stat (f i)) : Stat (route r o xs f) := match xs with | [] => sf o | (b,c)::xs => (statContact r o b c,statRoute r b xs f sf) def statSlot (r) (s : SlotCertificate) : Stat (s.query r) := ((),inferInstanceAs (Decidable _),statRoute _ _ _ _ (fun _ => statTerminal ..),isTrue trivial) def statPort (p) (a b : Node) : Stat (orientedPort p a b) := ((),(),(statEarly ..,statEarly ..),(),isTrue trivial) def statRight (n) (a b : Node) : Stat (rightward (P455PaddedTiles.system n) a b) := (horizontalD ..,statPort ..,(),isTrue trivial) def statDown (n) (a b : Node) : Stat (downward (P455PaddedTiles.system n) a b) := (verticalD ..,statPort ..) def statNeighbor (n) (a b : Node) : (d : Dir) → Stat (neighbor (P455PaddedTiles.system n) a b d) | .right | .left => statRight .. | .down | .up => statDown .. def statFunc (n) (f : FunctionalityCertificate) : Stat (f.query (P455PaddedTiles.system n)) := ((),statNeighbor ..,statNeighbor ..,(),isTrue trivial) def statFlag (b : Bool) {q : Query} (s : Stat q) : Stat (flagQ b q) := by cases b <;> first | exact s | exact isTrue trivial def statEdge (n) (e : EdgeCertificate) : Stat (e.query (P455PaddedTiles.system n)) := by refine ((),(),?_,?_,isTrue trivial) · exact (statFlag _ (statRight ..),statFlag _ (statRight ..),statFlag _ (statDown ..), statFlag _ (statDown ..),statFlag _ (statDown ..,statRight ..),isTrue trivial) · unfold chosenSuccessor dsimp only split · exact (inferInstanceAs (Decidable _),(statPort ..,statPort ..),(),isTrue trivial) · exact (inferInstanceAs (Decidable _),()) end P455Enum end /- Begin Problem455PrefixCommon (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455FirstRewrite P455FirstTesters P455Quotient def highNames (r : Nat) (u : Word) := (names u).filter (fun x => decide (r < u.count x)) def headPowers (r : Nat) (xs : Word) := xs.flatMap (List.replicate (r+1)) def residual (xs u : Word) := u.filter (fun a => decide (a ∉ xs)) @[simp] theorem mem_high (r x : Nat) (u : Word) : x ∈ highNames r u ↔ r < u.count x := by simp only [highNames,List.mem_filter,mem_names,decide_eq_true_eq] exact ⟨And.right,fun h => ⟨List.count_pos_iff.mp (by omega),h⟩⟩ @[simp] theorem residual_count (xs u : Word) (a : Nat) : (residual xs u).count a = if a ∈ xs then 0 else u.count a := by by_cases h : a ∈ xs · rw [if_pos h]; exact List.count_eq_zero.mpr (fun m => by simp [residual,h] at m) · simp [residual,List.count_filter,h] private theorem residual_step (x : Nat) (xs u : Word) : residual xs (dropName x u) = residual (x::xs) u := by simp only [residual,dropName,List.filter_filter] apply List.filter_congr intro a _ by_cases e : a = x <;> by_cases m : a ∈ xs <;> simp [e,m] private theorem handle_names {r allow ts} (xs u : Word) (dis : xs.Nodup) (many : ∀ x ∈ xs, r < u.count x) : Derives (Steps r allow ts) u (headPowers r xs ++ residual xs u) := by induction xs generalizing u with | nil => have empty : residual [] u = u := List.filter_eq_self.mpr (by simp) simpa only [headPowers,List.flatMap_nil,List.nil_append,empty] using (Walk.refl (s := Step (Steps r allow ts)) u) | cons x xs ih => obtain ⟨fresh,tail⟩ := List.nodup_cons.mp dis have p := gather_deduction (allow := allow) (ts := ts) u (many x List.mem_cons_self) have sat (a : Nat) (m : a ∈ xs) : r < (dropName x u).count a := by have ne : a ≠ x := fun e => fresh (e ▸ m) simpa only [drop_count,if_neg ne] using many a (List.mem_cons_of_mem _ m) have tailD := ih (dropName x u) tail sat have q := context_derives (List.replicate (r+1) x) [] tailD apply p.trans simpa only [headPowers,List.flatMap_cons,List.append_assoc,List.append_nil,residual_step,gather] using q private theorem residual_instance (xs u : Word) : u.flatMap (fun a => if a ∈ xs then [] else [a]) = residual xs u := by induction u with | nil => rfl | cons a t ih => by_cases h : a ∈ xs <;> simp [residual,h,ih] theorem residual_valid {A : Type} (M : Model A) (xs : Word) {u v : Word} (h : M.Valid u v) : M.Valid (residual xs u) (residual xs v) := by intro f rw [← residual_instance,← residual_instance,M.eval_instance,M.eval_instance] exact h _ /-- No input beyond validity of the original identity. The high names are explicitly computed on its left side and used in the same order on both. -/ theorem arbitrary_prefix {r allow ts} {u v : Word} (valid : (P455FullSingleton.model r allow ts).Valid u v) : let xs := highNames r u let p := headPowers r xs let a := residual xs u let b := residual xs v Derives (Steps r allow ts) u (p ++ a) ∧ Derives (Steps r allow ts) v (p ++ b) ∧ Cap r a ∧ Cap r b ∧ (P455FullSingleton.model r allow ts).Valid a b ∧ (∀ z, a.count z = b.count z) ∧ (a = [] ↔ b = []) := by dsimp only have power := tester_rule (valid_left _ _ valid) let xs := highNames r u have high (x : Nat) : r < u.count x ↔ r < v.count x := by have := power.unary x; omega have distinct : xs.Nodup := (names_distinct u).filter _ have cA : Cap r (residual xs u) := by intro a; rw [residual_count]; by_cases h : a ∈ xs · simp [h] · have lo : ¬ r < u.count a := fun n => h ((mem_high ..).mpr n) simp [h]; omega have cB : Cap r (residual xs v) := by intro a; rw [residual_count]; by_cases h : a ∈ xs · simp [h] · have lo : ¬ r < v.count a := fun n => h ((mem_high ..).mpr ((high a).mpr n)) simp [h]; omega have h := residual_valid _ xs valid have categories := tester_rule (valid_left _ _ h) have count (a : Nat) : (residual xs u).count a = (residual xs v).count a := by have := categories.unary a; have := cA a; have := cB a; omega refine ⟨handle_names xs u distinct (fun a m => (mem_high ..).mp m), handle_names xs v distinct (fun a m => (high a).mp ((mem_high ..).mp m)), cA,cB,h,count,?_⟩ exact ⟨fun e => (List.Perm.nil_eq (e ▸ List.perm_iff_count.mpr count)).symm, fun e => (List.Perm.nil_eq (e ▸ (List.perm_iff_count.mpr count).symm)).symm⟩ theorem lift_deduction {G H : Word → Word → Prop} (sub : ∀ a b, G a b → H a b) {u v : Word} (p : Derives G u v) : Derives H u v := by induction p with | refl => exact .refl _ | snoc _ step ih => obtain ⟨a,b,l,k,f,rule,an,bn,hn,left,right⟩ := step exact .snoc ih ⟨a,b,l,k,f,rule.imp (sub a b) (sub b a),an,bn,hn,left,right⟩ /-- Restore the common saturated prefix, inside an ordinary multiplication-only deduction, after any bounded derivation of the two capped suffixes. -/ theorem reassemble {r allow ts k} {u v : Word} (valid : (P455FullSingleton.model r allow ts).Valid u v) (suffixes : Derives (fun a b => (P455FullSingleton.model r allow ts).Valid a b ∧ rank a b ≤ k) (residual (highNames r u) u) (residual (highNames r u) v)) : Derives (fun a b => (P455FullSingleton.model r allow ts).Valid a b ∧ rank a b ≤ max k (2*(r+2)+1)) u v := by obtain ⟨left,right,_⟩ := arbitrary_prefix valid let H : Word → Word → Prop := fun a b => (P455FullSingleton.model r allow ts).Valid a b ∧ rank a b ≤ max k (2*(r+2)+1) have widen (a b) (h : Steps r allow ts a b) : H a b := ⟨h.1,Nat.le_trans h.2 (Nat.le_max_right ..)⟩ have a := lift_deduction widen left have b := lift_deduction widen right have middle := context_derives (headPowers r (highNames r u)) [] (lift_deduction (H := H) (fun _ _ h => ⟨h.1,Nat.le_trans h.2 (Nat.le_max_left ..)⟩) suffixes) have backwards := b.symm (fun step => P455ReductionBoundary.sym_step step) exact (a.trans (by simpa only [List.append_nil] using middle)).trans backwards end P455Prefix end /- Begin Problem455CellClassBinary (from finite-semigroup-identity-bases). -/ section namespace P455CellClassBinary open Problem455.Slots P455Witness P455FirstTesters P455FirstRewrite P455MarkedRank open P455BinaryEquality P455BinaryProduct P455SlotSaturation P455ProfileComponent abbrev W := List Nat theorem exact_counts {r allow ts U V} (cap : P455Quotient.Cap r U) (h : (P455FullSingleton.model r allow ts).Valid U V) (x : Nat) : U.count x = V.count x := by have ct := (tester_rule (valid_left _ _ h)).unary x have bd := cap x omega private theorem named {r allow ts U V} (h : (P455FullSingleton.model r allow ts).Valid U V) (i : P455BinaryProduct.Index r allow) (f : Nat → W) : P455Quotient.ofWord i.R i.T (U.flatMap f) = P455Quotient.ofWord i.R i.T (V.flatMap f) := by have idBin := ((valid_pair ..).mp (((valid_pair ..).mp ((valid_pair ..).mp h).2).2)).1 let g (a : Nat) (j : P455BinaryProduct.Index r allow) := P455Quotient.ofWord j.R j.T (f a) have eq := congrFun (idBin g) i rw [eval_at,eval_at,P455Quotient.eval_rep i.R i.bound _ U f (fun _ _ => rfl), P455Quotient.eval_rep i.R i.bound _ V f (fun _ _ => rfl)] at eq exact eq private theorem encoding (i j : Nat) (ne : i ≠ j) (U : W) : let E := U.flatMap (code i j) (∀ x ∈ E, x=0 ∨ x=1) ∧ E.count 0 = U.count i ∧ E.count 1 = U.count j ∧ E.length = U.count i + U.count j ∧ E.map (fun z => if z=0 then i else j) = select [i,j] U := by induction U with | nil => simp [select] | cons a U ih => obtain ⟨names,lo,hi,len,back⟩ := ih by_cases ai : a=i <;> by_cases aj : a=j <;> simp_all [List.flatMap_cons,code,List.count_cons,select,List.mem_cons, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc] <;> exact names /-- A change of two-name projection in a capped word is necessarily the change of the single bit of one admitted binary profile. Either input name can be its owner. All other names of V are unrestricted. -/ theorem changed {r allow ts U V} (cap : P455Quotient.Cap r U) (h : (P455FullSingleton.model r allow ts).Valid U V) {x y : Nat} (ne : x ≠ y) (diff : select [x,y] U ≠ select [x,y] V) : ∃ a b tag bit, ((a=x ∧ b=y) ∨ (a=y ∧ b=x)) ∧ tag.length+16=r ∧ allow tag ∧ select [x,y] U = profile a b tag bit ∧ select [x,y] V = profile a b tag (!bit) := by classical let f := code x y let T := U.flatMap f let S := V.flatMap f let d := fun z : Nat => if z=0 then x else y obtain ⟨names,c0,c1,len,decU⟩ := encoding x y ne U obtain ⟨_,_,_,_,decV⟩ := encoding x y ne V change T.map d = _ at decU change S.map d = _ at decV have neq : T ≠ S := fun same => diff (decU.symm.trans ((congrArg (List.map d) same).trans decV)) change T.length = U.count x + U.count y at len have capT : P455Quotient.Cap r T := by intro z; by_cases mem : z ∈ T · rcases names z mem with rfl|rfl · exact c0 ▸ cap x · exact c1 ▸ cap y · simp [List.count_eq_zero.mpr mem] have capV : P455Quotient.Cap r V := fun i => (exact_counts cap h i) ▸ cap i have pr (a b : Nat) (w : W) : proj a b w = select [a,b] w := by simp [proj,select] have pos (a b : Nat) (dif : proj a b U ≠ proj a b V) : 0 < U.count a ∧ 0 < U.count b := by obtain ⟨ea,eb⟩ := (tester_rule (valid_left _ _ h)).binary cap capV a b dif rcases Nat.eq_zero_or_pos r with zero|positive · have empty (u : W) (cp : P455Quotient.Cap r u) : u=[] := by cases u with | nil => rfl | cons z w => have := cp z; simp [zero] at this exact False.elim (dif (by rw [empty U cap, empty V capV])) · exact ⟨ea ▸ positive,eb ▸ positive⟩ obtain ⟨px,py⟩ := pos x y (by simpa only [pr] using diff) have covered := Problem455Finite.covered [0,1] (2*r) T (by have := cap x; have := cap y; omega) (fun z m => by simpa using names z m) obtain ⟨n,en⟩ := List.get_of_mem covered let i : P455BinaryProduct.Index r allow := ⟨n,decide (IsProfile r allow T),en.symm ▸ capT,by rw [en]; exact ⟨.inr ⟨c0 ▸ px,c1 ▸ py⟩,decide_eq_true_iff⟩⟩ have iT : i.T = T := en have ip : i.prof = decide (IsProfile r allow T) := rfl have same := named h i f change P455Quotient.ofWord i.R i.T T = P455Quotient.ofWord i.R i.T S at same have ps : IsProfile r allow T := by apply Classical.byContradiction intro no have rr : i.R = plain r := by simp [P455BinaryProduct.Index.R,ip,no] rw [iT,rr] at same have ok : P455Quotient.Good (plain r) T T := ⟨T,.refl _,[],[],by simp⟩ have path := ((P455Quotient.same_nonzero_class _ ok).mp same).2 exact neq (path.transport (P := fun z => T=z) rfl (fun bad _ => False.elim bad)) have rr : i.R = rules r allow noMark := by simp [P455BinaryProduct.Index.R,ip,ps] rw [iT,rr] at same obtain ⟨a,b,tag,bit,ab,tl,ok,et⟩ := ps have live : P455Quotient.Good (rules r allow noMark) T T := ⟨T,.refl _,[],[],by simp⟩ have path := ((P455Quotient.same_nonzero_class _ live).mp same).2 rw [et] at path obtain ⟨v,es⟩ := (variants ab tl ok bit S).mp path have opp : v = !bit := by cases v <;> cases bit <;> simp_all have az := names a (show a ∈ T by simp [et,profile,profilePrefix]) have bz := names b (show b ∈ T by simp [et,profile,profilePrefix]) refine ⟨d a,d b,tag,bit,?_,tl,ok,?_,?_⟩ · rcases az with h1|h1 <;> rcases bz with h2|h2 <;> simp_all [d] · exact decU.symm.trans ((congrArg (List.map d) et).trans (P455ContactReflection.map_profile ..)) · rw [← decV,es,opp,P455ContactReflection.map_profile] end P455CellClassBinary end /- Begin Problem455WordChart (from finite-semigroup-identity-bases). -/ section namespace P455WordChart open P455Witness P455Paths P455GridRows P455GraphReduction P455GridAssembly open P455SourceFamilies P455CrossedSupport P455ActualGuards P455SingletonEvaluation open P455SlotSaturation P455Uncrossed P455PortReflection P455Schedule P455FirstRewrite Problem455.Slots abbrev W := List Nat abbrev Walk (r : Nat) (allow : Tag → Prop) := P455Quotient.Walk (P455Closure.Move r allow noMark) private theorem free_if (p : Bool) (q : Query) (hq : markFree q=true) : markFree (flagQ p q)=true := by cases p <;> simp [flagQ,markFree,hq] private theorem free_local (ts : Tiles) (e : EdgeCertificate) : markFree (localCert ts e)=true := by have hr (a b : Node) : markFree (rightward ts a b)=true := rfl have hd (a b : Node) : markFree (downward ts a b)=true := rfl simp only [localCert,allQ,markFree,free_if _ _ (hr ..),free_if _ _ (hd ..)] rw [free_if _ _ (show markFree (.both (downward ts e.right e.diagonal) (rightward ts e.down e.diagonal))=true from rfl)] rfl private theorem free_successor (ts : Tiles) (e : EdgeCertificate) : markFree (chosenSuccessor ts e)=true := by dsimp only [chosenSuccessor]; split <;> rfl theorem remark_arrow {r allow mark mark' w ts e} (a : Arrow r allow mark w ts e) : Arrow r allow mark' w ts e := ⟨a.1,a.2.1,remark (free_local ..) a.2.2.1,remark (free_successor ..) a.2.2.2⟩ theorem walk_query {r allow u v} (p : Walk r allow u v) (q : Query) : Holds r allow noMark u q ↔ Holds r allow noMark v q := by induction p with | refl => rfl | snoc _ step ih => exact ih.trans (query_invariant step q) theorem walk_arrow {r allow u v ts e} (p : Walk r allow u v) : Arrow r allow noMark u ts e ↔ Arrow r allow noMark v ts e := by simp only [Arrow,← walk_query p] def Read (s : Bits) (nodes : Nat → Node) (r : Nat) (allow : Tag → Prop) (w : W) := ∀ i, Holds r allow noMark w (typedNode (nodes i)) → select [(nodes i).owner,(nodes i).mate] w = profile (nodes i).owner (nodes i).mate (nodes i).tag (s i) private theorem true_false_query {r allow ts u e} (edge : Arrow r allow noMark u ts e) (a : select [e.a.owner,e.a.mate] u = profile e.a.owner e.a.mate e.a.tag true) (b : select [e.b.owner,e.b.mate] u = profile e.b.owner e.b.mate e.b.tag false) : Holds r allow (fun _ _ => True) u (e.query ts) := by have h := remark_arrow (mark' := fun _ _ => True) edge exact ⟨⟨h.1.1,h.1.2.1,h.1.2.2.1,.inl trivial,a⟩, ⟨h.2.1.1,h.2.1.2.1,h.2.1.2.2.1,.inl trivial,b⟩,h.2.2.1,h.2.2.2,trivial⟩ def Changed (u v : W) (n : Node) := select [n.owner,n.mate] u ≠ select [n.owner,n.mate] v /-- The endpoint inequalities follow by looking at the actual edge tester of a hypothetical descending edge. No opposite-word shape is needed. -/ theorem good_of_identity {r allow ts U V w A} (nodes : Nat → Node) (C : List Nat) (cap : P455Closure.Cap r U) (valid : (P455FullSingleton.model r allow ts).Valid U V) (graph : Walk r allow w U) (read : Read A nodes r allow U) (diff : ∀ i ∈ C, Changed U V (nodes i)) : Good C (WordEdge r allow noMark w ts nodes) A := by intro a b ed member on obtain ⟨e,ea,eb,aU⟩ := ed have atU := (walk_arrow graph).mp aU have left := read a (ea ▸ atU.1) have right := read b (eb ▸ atU.2.1) rw [← ea,on] at left rw [← eb] at right cases off : A b with | true => rfl | false => rw [off] at right have mark := ((P455MarkedRank.valid_pair ..).mp ((P455MarkedRank.valid_pair ..).mp valid).2).1 have edge := ((P455MarkedRank.valid_pair ..).mp mark).2 have obs := P455EdgeProduct.endpoint_observed cap edge e (true_false_query atU left right) rcases member with mem|mem · exact False.elim (diff a mem (ea ▸ obs.1)) · exact False.elim (diff b mem (eb ▸ obs.2)) private theorem bit_inj {a b : Nat} (ne : a≠b) (tag : Tag) {i j : Bool} (e : profile a b tag i = profile a b tag j) : i=j := by cases i <;> cases j <;> simp_all [profile,pair] /-- Ordered roles are determined by a record on the unordered pair. Reversal would require both distinct letters to head the same projection. -/ theorem match_unique {r allow w} {n m : Node} (ok : Holds r allow noMark w (typedNode n)) (other : Holds r allow noMark w (typedNode m)) (match' : Matches m n.owner n.mate) : m=n := by rcases match' with ⟨x,y⟩|⟨x,y⟩ · exact P455PortUnique.node_unique m n x y other ok · obtain ⟨b,ob⟩ := ok.2.2.2 obtain ⟨c,oc⟩ := other.2.2.2 rw [x,y,select_pair_symm,ob] at oc have same := congrArg List.head? oc exact False.elim (ok.1 (by simpa [profile,profilePrefix] using same)) /-- Convert any failing incident marked edge into an actual descending graph edge. Coverage concerns typed records in the original word. -/ theorem feasible {r allow w ts v} (nodes : Nat → Node) (C : List Nat) (s : Bits) (p : Walk r allow w v) (read : Read s nodes r allow v) (cover : ∀ n, Holds r allow noMark w (typedNode n) → ∃ j, nodes j=n) (good : Good C (WordEdge r allow noMark w ts nodes) s) {i : Nat} (mem : i ∈ C) (typed : Holds r allow noMark w (typedNode (nodes i))) : ¬ EdgeViolation r allow ts v (nodes i).owner (nodes i).mate := by rintro ⟨e,side,mt,h⟩ have typedA : Holds r allow noMark v (typedNode e.a) := ⟨h.1.1,h.1.2.1,h.1.2.2.1,_,h.1.2.2.2.2⟩ have typedB : Holds r allow noMark v (typedNode e.b) := ⟨h.2.1.1,h.2.1.2.1,h.2.1.2.2.1,_,h.2.1.2.2.2.2⟩ have arrV : Arrow r allow noMark v ts e := ⟨typedA,typedB,remark (free_local ..) h.2.2.1,remark (free_successor ..) h.2.2.2.1⟩ have arr := (walk_arrow p).mpr arrV have typedI := (walk_query p _).mp typed obtain ⟨a,b,ea,eb,incident⟩ : ∃ a b, nodes a=e.a ∧ nodes b=e.b ∧ (a∈C ∨ b∈C) := by cases side with | false => obtain ⟨b,hb⟩ := cover _ arr.2.1 exact ⟨i,b,(match_unique typedI typedA mt).symm,hb,.inl mem⟩ | true => obtain ⟨a,ha⟩ := cover _ arr.1 exact ⟨a,i,ha,(match_unique typedI typedB mt).symm,.inr mem⟩ have la := read a (ea ▸ typedA) have lb := read b (eb ▸ typedB) rw [ea] at la rw [eb] at lb have one := bit_inj typedA.1 _ (la.symm.trans h.1.2.2.2.2) have zero := bit_inj typedB.1 _ (lb.symm.trans h.2.1.2.2.2.2) have twice := good a b ⟨e,ea.symm,eb.symm,arr⟩ incident one simp [zero] at twice end P455WordChart end /- Begin Problem455EnumStructural (from finite-semigroup-identity-bases). -/ section namespace P455Enum open P455Witness P455Structural P455PaddedTiles P455BinaryEquality Problem455.Slots theorem profile_names {a b tag bit} : a∈profile a b tag bit ∧ b∈profile a b tag bit := by simp [profile,profilePrefix] def profileD (r) (M : MachineTable n) (w : List Nat) : Decidable (IsProfile r (allowed M) w) := decidable_of_iff (∃ a∈w, ∃ b∈w, ∃ t∈tags M, ∃ bit : Bool, a≠b ∧ t.length+16=r ∧ w=profile a b t bit) (by constructor · rintro ⟨a,_,b,_,t,mt,v,ne,len,eq⟩; exact ⟨a,b,t,v,ne,len,mem_tags.mp mt,eq⟩ · rintro ⟨a,b,t,v,ne,len,mt,rfl⟩ exact ⟨a,profile_names.1,b,profile_names.2,t,mem_tags.mpr mt,v,ne,len,rfl⟩) def pairCover (a : Cover α) (b : Cover β) : Cover (α×β) := a.bind (fun _=>b) Prod.mk (fun ⟨x,y⟩=>⟨x,y,rfl⟩) def coverSub (s : Cover α) (p : α→Prop) [DecidablePred p] : Cover (Subtype p) := ⟨selectSub s.list p,fun i=>selectSub_full i (s.mem _)⟩ def binary (r) (M : MachineTable n) : Cover (P455BinaryProduct.Index r (allowed M)) := let xs := Problem455Finite.wordsUpTo [0,1] (2*r) let p (c : Fin xs.length × Bool) := let T:=xs.get c.1; P455Closure.Cap r T ∧ (T=P455FirstTesters.power r ∨ 0 by letI := capD r (xs.get c.1) letI := profileD r M (xs.get c.1) unfold p; dsimp only; infer_instance (coverSub (pairCover (fins _) bools) p).map (fun c=>⟨c.val.1,c.val.2,c.property.1,c.property.2⟩) (fun ⟨i,b,cp,ok⟩=>⟨⟨(i,b),cp,ok⟩,rfl⟩) theorem rec_names {r allow w a b} (h : Rec w r allow a b) : a∈w ∧ b∈w := by obtain ⟨t,_,_,_,bit,eq⟩ := h have m := @profile_names a b t bit rw [←eq] at m exact ⟨(List.mem_filter.mp m.1).1,(List.mem_filter.mp m.2).1⟩ theorem edge_names {r allow w a b} (h : Edge w r allow a b) : a∈w ∧ b∈w := h.elim rec_names (fun z => ⟨(rec_names z).2,(rec_names z).1⟩) instance recD (r) (M : MachineTable n) (w a b) : Decidable (Rec w r (allowed M) a b) := by unfold Rec exact @search _ (tags M) _ (fun t => by unfold Holds; infer_instance) (fun t z => mem_tags.mpr z.2.2.1) instance edgeD (r) (M : MachineTable n) (w a b) : Decidable (Edge w r (allowed M) a b) := by unfold Edge; infer_instance theorem words_bound {α : Type} (alphabet : List α) (k) {w : List α} (mem : w∈Problem455Finite.wordsUpTo alphabet k) : w.length≤k := by induction k generalizing w with | zero => simpa [Problem455Finite.wordsUpTo] using mem | succ k ih => rcases List.mem_cons.mp mem with rfl|tail · simp obtain ⟨a,_,hit⟩ := List.mem_flatMap.mp tail obtain ⟨q,m,rfl⟩ := List.mem_map.mp hit exact Nat.succ_le_succ (ih m) def widthD (k : Nat) (w : List Nat) : Decidable (Width k w) := decidable_of_iff (∃ C∈Problem455Finite.wordsUpTo w k,∀ x∈w,x∈C) (by constructor · rintro ⟨C,h,c⟩ exact ⟨C,words_bound _ _ h,c⟩ · rintro ⟨C,len,c⟩ let V := C.filter (fun x=>x∈w) have toV (x) (m : x∈w) : x∈V := by simp [V,c _ m,m] exact ⟨V,Problem455Finite.covered _ _ _ (Nat.le_trans (List.length_filter_le ..) len) (fun _ m => of_decide_eq_true (List.mem_filter.mp m).2),toV⟩) def overlapD (r) (M : MachineTable n) (w) : Decidable (Overlap w r (allowed M)) := decidable_of_iff (∃ o∈w, ∃ p∈w, ∃ q∈w, o≠p ∧ o≠q ∧ p≠q ∧ Edge w r (allowed M) o p ∧ Edge w r (allowed M) o q) ⟨fun ⟨o,_,p,_,q,_,h⟩=>⟨o,p,q,h⟩,fun ⟨o,p,q,h⟩ => ⟨o,(edge_names h.2.2.2.1).1,p,(edge_names h.2.2.2.1).2,q,(edge_names h.2.2.2.2).2,h⟩⟩ def intrusionD (r) (M : MachineTable n) (w) : Decidable (Intrusion w r (allowed M)) := decidable_of_iff (∃ o∈w, ∃ p∈w, ∃ e∈events w, o≠p ∧ e.1≠o ∧ e.1≠p ∧ Rec w r (allowed M) o p ∧ sees w [(o,0),e,(p,2)]) ⟨fun ⟨o,_,p,_,e,_,h⟩=>⟨o,p,e.1,e.2,h⟩,fun ⟨o,p,z,j,h⟩=> ⟨o,(rec_names h.2.2.2.1).1,p,(rec_names h.2.2.2.1).2,(z,j),h.2.2.2.2.subset (by simp),h⟩⟩ def compressedD {r} (hr : 0f _ (linkNames hr lk).1 _ (linkNames hr lk).2 lk,fun f a _ b _=>f a b⟩ def structural {r} (hr : 0 by let w:=xs.get i letI := capD r w; letI := compressedD hr w letI := widthD 4 w; letI := widthD 3 w; letI := overlapD r M w; letI := intrusionD r M w unfold p Structural; dsimp only; infer_instance (coverSub (fins _) p).map (fun c=>⟨c.val,c.property.1,c.property.2.1,c.property.2.2⟩) (fun ⟨i,cp,cmp,st⟩=>⟨⟨i,cp,cmp,st⟩,rfl⟩) end P455Enum end /- Begin Problem455PrefixBlocks (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455FirstRewrite P455Quotient open Problem455Swap (Link bigram hit) def openPair (a b z : Nat) : Word := if z = a then [a,b] else [z] private theorem out_le (a b : Nat) (w : Word) : bigram a b w ≤ w.count a := by have h := Problem455Swap.out_bound a b (b+1) (by omega) w rw [Problem455BlockBridge.occ_count] at h; omega private theorem in_le (a b : Nat) (w : Word) : bigram a b w ≤ w.tail.count b := by have h := Problem455Swap.in_bound a (a+1) b (by omega) w rw [Problem455BlockBridge.occ_count] at h; omega theorem link_counts {r a b} {w : Word} (c : Cap r w) (l : Link r w a b) : w.count a = r ∧ w.count b = r := by have h := out_le a b w have j := in_le a b w have t := Problem455Swap.tail_occ_le b w simp only [Problem455BlockBridge.occ_count] at t have ca := c a; have cb := c b change bigram a b w = r at l omega private theorem parse {a b : Nat} (w : Word) (ca : bigram a b w = w.count a) (cb : bigram a b w = w.count b) : (dropName b w).flatMap (openPair a b) = w := by cases w with | nil => rfl | cons z t => have nb : z ≠ b := by rintro rfl have h := in_le a z (z::t) simp [List.count_cons] at cb h; omega by_cases za : z = a · subst z cases t with | nil => simp [bigram,hit,List.count_cons] at ca | cons c s => have next : c = b := by apply Classical.byContradiction; intro h have lower := out_le a b (c::s) simp [bigram,hit,h,List.count_cons] at ca simp [bigram,hit,List.count_cons] at lower omega subst c have size : bigram a b (a::b::s) = 1+bigram a b s := by simp [bigram,hit,Ne.symm nb] rw [size] at ca cb simp [List.count_cons,nb,Ne.symm nb] at ca cb have eq := parse s (by omega : bigram a b s = s.count a) (by omega : bigram a b s = s.count b) simpa [dropName,openPair,nb] using congrArg (List.cons a ∘ List.cons b) eq · have same : bigram a b (z::t) = bigram a b t := by simp [bigram,hit,za] rw [same] at ca cb simp [List.count_cons,za,nb] at ca cb simpa [dropName,openPair,za,nb] using congrArg (List.cons z) (parse t ca cb) termination_by w.length theorem recover_link {r a b} {w : Word} (cap : Cap r w) (l : Link r w a b) : (dropName b w).flatMap (openPair a b) = w := by obtain ⟨p,q⟩ := link_counts cap l exact parse w (l.trans p.symm) (l.trans q.symm) private theorem drop_length (b : Nat) (w : Word) : (dropName b w).length + w.count b = w.length := by induction w with | nil => rfl | cons a t ih => by_cases e : a=b <;> simp_all [dropName,List.count_cons] <;> omega private theorem drop_cap {r} (b : Nat) {w : Word} (cap : Cap r w) : Cap r (dropName b w) := by intro a; rw [drop_count]; split · omega · exact cap a private theorem drop_valid {A : Type} (M : Model A) (b : Nat) {u v : Word} (h : M.Valid u v) : M.Valid (dropName b u) (dropName b v) := by have eq (z : Word) : residual [b] z = dropName b z := by unfold residual dropName; apply List.filter_congr; intro a _; by_cases e : a=b <;> simp [e] simpa only [eq] using residual_valid M [b] h private theorem nonempty_composition {f g : Nat → Word} (hf : ∀ z, f z ≠ []) (hg : ∀ z, g z ≠ []) (z : Nat) : (f z).flatMap g ≠ [] := by obtain ⟨a,m⟩ := List.exists_mem_of_ne_nil _ (hf z) exact fun nil => hg a ((List.flatMap_eq_nil_iff.mp nil) a m) def Asymmetric (r : Nat) (u v : Word) : Prop := ∃ a b, (Link r u a b ∧ ¬ Link r v a b) ∨ (Link r v a b ∧ ¬ Link r u a b) /-- During contraction new projected links need not be predicted in advance. Recompute common links, decrease length, and compose their nonempty inverses. -/ theorem contract_common {r allow ts} (hr : 0 < r) (u v : Word) (cu : Cap r u) (cv : Cap r v) (valid : (P455FullSingleton.model r allow ts).Valid u v) : ∃ A B : Word, ∃ h : Nat → Word, (∀ x, h x ≠ []) ∧ A.flatMap h = u ∧ B.flatMap h = v ∧ Cap r A ∧ Cap r B ∧ (P455FullSingleton.model r allow ts).Valid A B ∧ (∀ a b, ¬ (Link r A a b ∧ Link r B a b)) ∧ ((P455SourceFamilies.Compressed r A ∧ P455SourceFamilies.Compressed r B) ∨ Asymmetric r A B) := by classical by_cases common : ∃ a b, Link r u a b ∧ Link r v a b · obtain ⟨a,b,ul,vl⟩ := common have hlt : (dropName b u).length < u.length := by have c := (link_counts cu ul).2; have l := drop_length b u; omega obtain ⟨A,B,h,non,hu,hv,ca,cb,hvld,last,done⟩ := contract_common hr (dropName b u) (dropName b v) (drop_cap b cu) (drop_cap b cv) (drop_valid _ b valid) have op (z) : openPair a b z ≠ [] := by by_cases e : z=a <;> simp [openPair,e] refine ⟨A,B,fun z => (h z).flatMap (openPair a b),nonempty_composition non op,?_,?_,ca,cb,hvld,last,done⟩ · rw [← List.flatMap_assoc,hu,recover_link cu ul] · rw [← List.flatMap_assoc,hv,recover_link cv vl] · have no (a b : Nat) := fun both => common ⟨a,b,both⟩ refine ⟨u,v,fun a => [a],by simp,by simp,by simp,cu,cv,valid,no,?_⟩ by_cases all : P455SourceFamilies.Compressed r u ∧ P455SourceFamilies.Compressed r v · exact .inl all · right by_cases one : ∃ a b, Link r u a b · obtain ⟨a,b,l⟩ := one; exact ⟨a,b,.inl ⟨l,fun j => no a b ⟨l,j⟩⟩⟩ · by_cases two : ∃ a b, Link r v a b · obtain ⟨a,b,l⟩ := two; exact ⟨a,b,.inr ⟨l,fun j => no a b ⟨j,l⟩⟩⟩ · exact (all ⟨fun a b l => one ⟨a,b,l⟩,fun a b l => two ⟨a,b,l⟩⟩).elim termination_by u.length /-- Apply an inverse block expansion throughout a semigroup derivation even when its rule substitutions already have multi-letter images. -/ theorem substitute_deduction {G : Word → Word → Prop} (h : Nat → Word) (non : ∀ x, h x ≠ []) {A B : Word} (d : Derives G A B) : Derives G (A.flatMap h) (B.flatMap h) := by induction d with | refl => exact .refl _ | snoc _ step ih => obtain ⟨a,b,l,k,f,rule,an,bn,fn,rfl,rfl⟩ := step exact .snoc ih ⟨a,b,l.flatMap h,k.flatMap h,fun z => (f z).flatMap h,rule,an,bn, nonempty_composition fn non,by simp [List.flatMap_assoc],by simp [List.flatMap_assoc]⟩ end P455Prefix end /- Begin Problem455Alignment (from finite-semigroup-identity-bases). -/ section /- A matching of inverted comparisons of indexed positions forces literal adjacent transpositions. This argument works directly on arbitrary permutations, without choosing a pre-existing cell layout. -/ namespace P455Alignment open P455Witness P455Paths P455ContactReflection Problem455.Slots def Inverted {α : Type} (u v : List α) (a b : α) := [a,b].Sublist u ∧ [b,a].Sublist v inductive Blocks {α : Type} (mates : α → α → Prop) : List α → List α → Prop where | nil : Blocks mates [] [] | fixed (x) {u v} : Blocks mates u v → Blocks mates (x::u) (x::v) | pair (x y) {u v} : mates x y → Blocks mates u v → Blocks mates (x::y::u) (y::x::v) private theorem prep {α : Type} (a : α) {b : α} {w : List α} (inW : b ∈ w) : [a,b].Sublist (a::w) := (List.singleton_sublist.mpr inW).cons₂ a private theorem second {α : Type} [DecidableEq α] {a b : α} {u v : List α} (neq : a≠b) (distinct : (a::u).Nodup) (same : (a::u).Perm (b::v)) (M : α → α → Prop) (sym : ∀ {x y}, M x y → M y x) (unique : ∀ {x y z}, M x y → M x z → y=z) (cross : ∀ x y, Inverted (a::u) (b::v) x y → M x y) : ∃ t, u=b::t := by have bu := (List.mem_cons.mp (same.mem_iff.mpr (List.mem_cons_self : b ∈ b::v))).resolve_left (Ne.symm neq) have av := (List.mem_cons.mp (same.mem_iff.mp (List.mem_cons_self : a ∈ a::u))).resolve_left neq have ba := sym (cross _ _ ⟨prep _ bu,prep _ av⟩) cases u with | nil => contradiction | cons c t => by_cases e : c=b · exact ⟨t,by rw [e]⟩ have bt := (List.mem_cons.mp bu).resolve_left (Ne.symm e) have cv := (List.mem_cons.mp (same.mem_iff.mp (show c∈a::c::t by simp))).resolve_left e have bc := sym (cross _ _ ⟨(prep c bt).cons a,prep b cv⟩) have ca := unique bc ba exact False.elim ((List.nodup_cons.mp distinct).1 (ca ▸ List.mem_cons_self)) /-- If each inverted pair is an edge of a matching, the original words split into the same sequence of singles and disjoint transposed pairs. -/ theorem align {α : Type} [DecidableEq α] (M : α → α → Prop) (sym : ∀ {x y}, M x y → M y x) (unique : ∀ {x y z}, M x y → M x z → y=z) (u v : List α) (distinct : u.Nodup) (same : u.Perm v) (cross : ∀ x y, Inverted u v x y → M x y) : Blocks M u v := by cases u with | nil => obtain rfl := same.nil_eq; exact .nil | cons a u => cases v with | nil => cases same.length_eq | cons b v => by_cases eq : a=b · subst b exact .fixed a (align M sym unique u v (List.nodup_cons.mp distinct).2 ((List.perm_cons _).mp same) (fun x y e => cross x y ⟨e.1.cons a,e.2.cons a⟩)) · obtain ⟨u',rfl⟩ := second eq distinct same M sym unique cross obtain ⟨v',rfl⟩ := second (Ne.symm eq) (same.nodup_iff.mp distinct) same.symm M sym unique (fun x y h => sym (cross y x ⟨h.2,h.1⟩)) have aligned : (a::b::u').Perm (a::b::v') := same.trans (.swap _ _ _) have common := (List.perm_cons _).mp ((List.perm_cons _).mp aligned) have pair := cross a b ⟨prep _ List.mem_cons_self,prep _ List.mem_cons_self⟩ exact .pair a b pair (align M sym unique u' v' ((List.nodup_cons.mp (List.nodup_cons.mp distinct).2).2) common (fun x y e => cross x y ⟨(e.1.cons b).cons a,(e.2.cons a).cons b⟩)) termination_by u.length end P455Alignment end /- Begin Problem455CellClass (from finite-semigroup-identity-bases). -/ section /- Reconstruct every word identical to the zero-bit word from its binary projections. The only final-phase assumption is a literal projection of the given tail; it holds for the canonical final phase. -/ namespace P455CellClass open P455RectangleRank P455FirstRewrite P455Witness P455Structural Problem455.Slots abbrev W := List Nat def samePair (x y i : Nat) : Prop := (x = owner i ∧ y = mate i) ∨ (x = mate i ∧ y = owner i) private theorem roles (x : Nat) : x = owner (x/2) ∨ x = mate (x/2) := by unfold owner mate; omega theorem private_closed {t i} (ix : i < t) (middle tail : W) (bit : Nat → Bool) : Closed (word t middle tail bit) (owner i) (mate i) := by let lower := (List.range i).flatMap privateCell let higher := ((List.range (t-(i+1))).map (fun x => i+1+x)).flatMap privateCell have eq : List.range t = (List.range i ++ [i]) ++ (List.range (t-(i+1))).map (fun x => i+1+x) := by conv => lhs; arg 1; rw [show t=(i+1)+(t-(i+1)) by omega] rw [List.range_add,List.range_succ] have pre (x : Nat) (inside : x=owner i ∨ x=mate i) : x ∉ lower := by intro m obtain ⟨j,mj,h⟩ := List.mem_flatMap.mp m have lt := List.mem_range.mp mj have rr : x=owner j ∨ x=mate j := by simpa [privateCell,or_assoc,or_left_comm,or_comm] using h unfold owner mate at *; omega refine ⟨by simp [owner,mate],lower,higher ++ middle ++ (List.range t).flatMap (mutableCell bit) ++ tail,?_, pre _ (.inl rfl),pre _ (.inr rfl)⟩ unfold word conv => lhs; arg 1; arg 1; arg 1; rw [eq] simp [lower,higher,early,privateCell,List.append_assoc,List.flatMap_append] theorem only_cell {r allow ts t middle tail V} (small : ∀ x ∈ middle ++ tail, x < 2*t) (cap : P455Quotient.Cap r (word t middle tail (constant false))) (ident : (P455FullSingleton.model r allow ts).Valid (word t middle tail (constant false)) V) {x y} (ne : x ≠ y) (diff : select [x,y] (word t middle tail (constant false)) ≠ select [x,y] V) : ∃ i < t, samePair x y i := by let U := word t middle tail (constant false) obtain ⟨a,b,tag,bit,order,len,allowT,src,_⟩ := P455CellClassBinary.changed cap ident ne diff have edge : Edge U r allow x y := by rcases order with ⟨rfl,rfl⟩|⟨rfl,rfl⟩ · exact .inl ⟨tag,ne,len,allowT,bit,src⟩ · exact .inr ⟨tag,Ne.symm ne,len,allowT,bit,(select_pair_symm _ _ _).trans src⟩ have xproj : x ∈ select [x,y] (word t middle tail (constant false)) := by rw [src]; rcases order with ⟨rfl,rfl⟩|⟨rfl,rfl⟩ <;> simp [profile,profilePrefix] have xlt := word_names _ small x (List.mem_filter.mp xproj).1 have lt : x/2 < t := by omega have xc := roles x have yc : y=owner (x/2) ∨ y=mate (x/2) := by apply Classical.byContradiction; intro bad exact (no_external_record (private_closed lt middle tail _) xc ⟨fun h => bad (.inl h),fun h => bad (.inr h)⟩) edge exact ⟨x/2,lt,by unfold samePair; omega⟩ private theorem mutable_own (cells : List Nat) (nd : cells.Nodup) (bit : Nat → Bool) (i : Nat) : select [owner i,mate i] (cells.flatMap (mutableCell bit)) = (if i ∈ cells then mutableCell bit i else []) := by induction cells with | nil => simp [select] | cons j cells ih => rw [List.flatMap_cons,select_append,ih (List.nodup_cons.mp nd).2] by_cases eq : i=j · subst j have fresh := (List.nodup_cons.mp nd).1 cases b : bit i <;> simp [mutableCell,b,fresh,select] · have no : select [owner i,mate i] (mutableCell bit j) = [] := by apply select_nil intro z m have either : z=owner j ∨ z=mate j := by cases b : bit j <;> simpa [mutableCell,b,or_comm] using m simp only [List.mem_cons,List.not_mem_nil,or_false] unfold owner mate at *; omega simp [no,eq] private def stem (t : Nat) (middle : W) := (List.range t).flatMap privateCell ++ middle private theorem own {t i} (ix : i rfl | cons i cells ih => simp only [List.flatMap_cons, select_append] rw [kept_other x y i (all i List.mem_cons_self) bit, ih (fun j hj => all j (List.mem_cons_of_mem _ hj))] unfold word simp only [select_append,go _ (fun i m => none i (List.mem_range.mp m))] private theorem reverse_names (w : W) (x y : Nat) : select [x,y] w = select [y,x] w := by exact select_pair_symm _ _ _ private theorem mono (w : W) (x : Nat) : select [x,x] w = List.replicate (w.count x) x := by induction w with | nil => simp [select] | cons z w ih => by_cases eq : z=x <;> simp_all [select,List.count_cons,List.replicate_succ] /-- No restriction is imposed on the comparison word. The middle may contain arbitrary occurrences on the prescribed cell names. -/ theorem represent {r allow ts t middle tail V} (small : ∀ x ∈ middle ++ tail, x < 2*t) (cap : P455Quotient.Cap r (word t middle tail (constant false))) (finalPair : ∀ i < t, select [owner i,mate i] tail = [owner i,mate i]) (valid : (P455FullSingleton.model r allow ts).Valid (word t middle tail (constant false)) V) : ∃ bit, V = word t middle tail bit := by classical let U := word t middle tail (constant false) let bit := fun i => decide (select [owner i,mate i] U ≠ select [owner i,mate i] V) have sameCell (i : Nat) (ix : i simp only [pair,if_true,if_false,List.length_append,List.length_cons, List.length_nil,Bool.false_eq_true] at len <;> omega obtain ⟨ke,rest⟩ := List.append_inj e kl have ab : a=x ∧ b=y ∧ c=false := by cases c <;> simp [pair] at rest ⊢ <;> omega obtain ⟨rfl,rfl,rfl⟩ := ab rw [own ix middle tail bit (finalPair i ix)] simpa [profile,pair,mutableCell,hb,K,x,y] using comp.trans (by change profile x y tag true = K ++ [y,x,x,y] rw [ke]; rfl) refine ⟨bit,P455BlockSeparators.pair_ext (fun x y => ?_)⟩ by_cases used : ∃ i used ⟨i,ix,yes⟩ rw [other middle tail bit notUsed] by_cases eq : x=y · subst y; rw [mono,mono,P455CellClassBinary.exact_counts cap valid x] · apply Classical.byContradiction; intro diff exact used (only_cell small cap valid eq (Ne.symm diff)) theorem canonical_final (t i : Nat) (ix : i < t) : select [owner i,mate i] ((List.range t).flatMap (mutableCell (constant false))) = [owner i,mate i] := by rw [mutable_own _ List.nodup_range,if_pos (List.mem_range.mpr ix)]; rfl theorem bit_change {t i : Nat} (ix : i cases value <;> simp [mutableCell,bi,pair] at len <;> omega) have matchBit : value=bit i := by cases bi : bit i <;> cases value <;> simp_all [mutableCell,pair] exact matchBit ▸ eq end P455CellClass end /- Begin Problem455ChartSchedule (from finite-semigroup-identity-bases). -/ section namespace P455ChartSchedule open P455Witness P455FirstRewrite P455GraphReduction P455GridAssembly P455GridRows open P455SourceFamilies P455SlotSaturation P455Schedule P455Uncrossed P455CrossedSupport open P455ReductionBoundary P455WordChart P455ActualGuards Problem455.Slots abbrev W := List Nat def switch (s : Bits) (i : Nat) : Bits := fun j => if j=i then !s j else s j def Off (C : List Nat) (A s : Bits) := ∀ j, j ∉ C → s j=A j structure Literal (r : Nat) (allow : Tag → Prop) (u v : W) (n : Node) where f : P455Closure.Frame Nat bit : Bool l : W k : W owner : f.p=[n.owner] mate : f.q=[n.mate] shape : f.Valid r allow noMark source : u=side f l k bit target : v=side f l k (!bit) theorem Literal.step {r allow u v n} (g : Literal r allow u v n) (cp : P455Closure.Cap r u) : P455Closure.Move r allow noMark u v := ⟨g.f,g.bit,g.l,g.k,g.shape,g.source,g.target,cp⟩ theorem walk_cap {r allow u v} (h : P455WordChart.Walk r allow u v) (cap : P455Closure.Cap r u) : P455Closure.Cap r v := h.transport cap (fun mv _ => mv.cap_right) private theorem walk_compressed {r allow u v} (h : P455WordChart.Walk r allow u v) (cmp : Compressed r u) : Compressed r v := h.transport cmp (fun mv old a b link => old a b ((Problem455BlockBridge.move_link mv a b).mpr link)) /-- Only assignments which agree with A on fixed records are represented. A one-bit change is a word equation describing factors and contexts, with no claim that the change is a valid identity in the monoid. -/ structure Geometry (r : Nat) (allow : Tag → Prop) (C : List Nat) (A : Bits) (word : Bits → W) (nodes : Nat → Node) : Prop where cover : ∀ n, Holds r allow noMark (word A) (typedNode n) → ∃ j, nodes j=n active : ∀ i ∈ C, Holds r allow noMark (word A) (typedNode (nodes i)) value : ∀ s, Off C A s → Read s nodes r allow (word s) flip : ∀ s, Off C A s → ∀ i ∈ C, Nonempty (Literal r allow (word s) (word (switch s i)) (nodes i)) private theorem off_switch {A s C i} (off : Off C A s) (mem : i ∈ C) : Off C A (switch s i) := by intro j nj have ne : j≠i := fun e => nj (e ▸ mem) simpa [switch,ne] using off j nj /-- Reach any prescribed bit assignment by literal unmarked moves. The cap is propagated through real moves and repeated indices in C are harmless. -/ theorem reach {r allow C A word nodes} (g : Geometry r allow C A word nodes) (B : Bits) (offB : Off C A B) (cp : P455Closure.Cap r (word A)) : P455WordChart.Walk r allow (word A) (word B) := by have fill (xs : List Nat) (sub : ∀ i∈xs, i∈C) : ∃ s, Off C A s ∧ P455WordChart.Walk r allow (word A) (word s) ∧ ∀ i∈xs, s i=B i := by induction xs with | nil => exact ⟨A,fun _ _ => rfl,.refl _,by simp⟩ | cons i xs ih => obtain ⟨s,off,path,eq⟩ := ih (fun j mem => sub j (List.mem_cons_of_mem i mem)) by_cases done : s i=B i · exact ⟨s,off,path,fun j mem => (List.mem_cons.mp mem).elim (fun ji => ji ▸ done) (eq j)⟩ have ci := sub i List.mem_cons_self obtain ⟨f⟩ := g.flip s off i ci refine ⟨switch s i,off_switch off ci,.snoc path (f.step (walk_cap path cp)),?_⟩ intro j mem by_cases ji : j=i · subst j; cases h : s i <;> cases z : B i <;> simp_all [switch] · simpa [switch,ji] using eq j ((List.mem_cons.mp mem).resolve_left ji) obtain ⟨s,off,path,hit⟩ := fill C (fun _ h => h) have eq : s=B := funext fun i => by by_cases hi : i∈C · exact hit i hi · exact (off i hi).trans (offB i hi).symm exact eq ▸ path /-- No acyclicity, functionality, admissibility of a mixed bit word, edge inequalities or bounded deductions are input hypotheses. -/ theorem normalize_layout {r allow ts C A B word nodes} (law : Laws ts) (g : Geometry r allow C A word nodes) (offB : Off C A B) (different : ∀ i∈C, A i≠B i) (cap : P455Closure.Cap r (word A)) (cmp : Compressed r (word A)) (valid : (P455FullSingleton.model r allow ts).Valid (word A) (word B)) : Derives (fun u v => (P455FullSingleton.model r allow ts).Valid u v ∧ rank u v ≤ P455MarkedRank.bound r) (word A) (word B) ∨ Nonempty (Rectangle allow ts) := by classical let E := WordEdge r allow noMark (word A) ts nodes have allA : Off C A A := fun _ _ => rfl have AB := reach g B offB cap have diff (i : Nat) (hi : i∈C) : Changed (word A) (word B) (nodes i) := by have typed := g.active i hi have left := g.value A allA i typed have right := g.value B offB i ((walk_query AB _).mp typed) intro eq have cross := left.symm.trans (eq.trans right) have distinct := different i hi cases x : A i <;> cases y : B i <;> simp_all [profile,pair,typed.1,Ne.symm typed.1] have funct (i : Nat) (mem : i∈C) : Functional r allow noMark (word A) ts (nodes i) := P455PortUnique.functional cap (P455FullSingleton.guard_valid valid) (diff i mem) (.refl _) cmp _ (.inl ⟨rfl,rfl⟩) (g.active i mem) by_cases loop : ∃ a, Path (induced C E) a a · obtain ⟨a,p⟩ := loop exact .inr (rectangle_of_cycle law nodes C funct p) have goodA : Good C E A := good_of_identity nodes C cap valid (.refl _) (g.value _ allA) diff have goodB : Good C E B := good_of_identity nodes C (walk_cap AB cap) (fun f => (valid f).symm) AB (g.value _ offB) (fun i h eq => diff i h eq.symm) have fixed (a : Nat) (ne : A a≠B a) : a∈C := by apply Classical.byContradiction; intro out; exact ne (offB a out).symm have sched := schedule (C := C) (E := E) (fun a p => loop ⟨a,p⟩) A B goodA goodB fixed have steps (s : Bits) (path : P455Quotient.Walk (Toward C E B) A s) : Off C A s ∧ Derives (fun u v => (P455FullSingleton.model r allow ts).Valid u v ∧ rank u v ≤ P455MarkedRank.bound r) (word A) (word s) := by induction path with | refl => exact ⟨allA,.refl _⟩ | @snoc s t _ flip ih => obtain ⟨gs,gt,i,mem,_,ne,others⟩ := flip have alt : t = switch s i := funext fun j => by by_cases ji : j=i · subst j; cases x : s i <;> cases y : t i <;> simp_all [switch] · simpa [switch,ji] using (others j ji).symm have ot : Off C A t := alt ▸ off_switch ih.1 mem have ps := reach g s ih.1 cap have pt := reach g t ot cap obtain ⟨f⟩ := g.flip s ih.1 i mem obtain ⟨f0⟩ := g.flip A allA i mem have tgt : word t=side f.f f.l f.k (!f.bit) := alt ▸ f.target have cs := walk_cap ps cap have ct := walk_cap pt cap have pair0 : P455Closure.Cap r (side f.f f.l f.k false) := by cases b : f.bit · simpa only [f.source,b] using cs · simpa only [tgt,b,Bool.not_true] using ct have noS := feasible nodes C s ps (g.value s ih.1) g.cover gs mem (g.active i mem) have noT := feasible nodes C t pt (g.value t ot) g.cover gt mem (g.active i mem) have localok (b : Bool) : ¬EdgeViolation r allow ts (side f.f f.l f.k b) (nodes i).owner (nodes i).mate := by rw [f.source] at noS; rw [tgt] at noT cases fb : f.bit <;> cases b <;> simp_all let layout : P455ReductionBoundary.Layout r allow ts (word A) (word B) (word s) (word t) := ⟨(nodes i).owner,(nodes i).mate,f.f,f.l,f.k,f.bit,f.owner,f.mate,f.shape,pair0, ⟨f0.f,f0.bit,f0.l,f0.k,f0.owner,f0.mate,f0.shape,f0.source⟩,diff i mem, f.source ▸ ps,f.source ▸ walk_compressed ps cmp,localok,f.source,tgt⟩ exact ⟨ot,.snoc ih.2 (layout.step cap valid)⟩ exact .inl (steps B sched).2 end P455ChartSchedule end /- Begin Problem455EnumGuards (from finite-semigroup-identity-bases). -/ section namespace P455Enum open P455Witness P455Paths P455PaddedTiles P455CatalogueBounds P455GuardProduct Problem455.Slots def choices (ts : List Tag) : List ContactChoice := ts.flatMap (fun t => bools.list.map (.record t)) ++ (fins 5).list.flatMap (fun p=>bools.list.map (.port p)) def steps (w : List Nat) (ts : List Tag) : List Step := w.flatMap fun b => (choices ts).map (Prod.mk b) theorem occMem {w o i a} (h : occupies w o i a) : a∈w := by obtain ⟨j,pat⟩ := h exact Problem455.Slots.stamped_mem_label _ _ (a,j) (pat.subset (by simp)) theorem step_mem {r w mark a b c} (M : MachineTable n) (h : Holds r (allowed M) mark w (contact r a b c)) : (b,c)∈steps w (tags M) := by have cell := P455ContactGeometry.contact_slot h obtain ⟨_,_,occ⟩ := cell apply List.mem_flatMap.mpr refine ⟨b,occMem occ,List.mem_map.mpr ⟨c,?_,rfl⟩⟩ unfold choices cases c with | port p v => exact List.mem_append_right _ (List.mem_flatMap.mpr ⟨p,(fins 5).mem _,List.mem_map_of_mem (bools.mem v)⟩) | record t v => have allow : allowed M t := by cases v <;> exact h.2.2.1 exact List.mem_append_left _ (List.mem_flatMap.mpr ⟨t,mem_tags.mpr allow,List.mem_map_of_mem (bools.mem v)⟩) theorem walk_steps {r w mark start} (M : MachineTable n) (p : List Step) (walk : Walk r (allowed M) mark w start p) : ∀ e∈p,e∈steps w (tags M) := by induction p generalizing start with | nil => simp | cons e es ih => rcases e with ⟨b,c⟩ intro z mz exact (List.mem_cons.mp mz).elim (fun eq=>eq ▸ step_mem M walk.1) (ih walk.2 z) def defects (w : List Nat) := w.map SlotDefect.deficient ++ (Problem455Finite.wordsUpTo w 5).map SlotDefect.overflow theorem defect_mem {r allow mark w o i} (d : SlotDefect) (valid : Holds r allow mark w (terminalSlot r o i d)) : d∈defects w := by cases d with | deficient a => exact List.mem_append_left _ (List.mem_map_of_mem (occMem valid.1.2)) | overflow xs => have pos (a) (m : a∈xs) : w.count a=r ∧ slotStart i ∧ occupies w o i a := (allQ_iff _).mp valid.2.2.1 _ (List.mem_map_of_mem m) exact List.mem_append_right _ (List.mem_map_of_mem (Problem455Finite.covered _ _ xs (Nat.le_of_eq valid.1) (fun a m => occMem (pos a m).2.2))) def slots (w : List Nat) (ts : List Tag) : List SlotCertificate := (pool w ts).flatMap fun a=>bools.list.flatMap fun b=>bools.list.flatMap fun role=> (Problem455Finite.wordsUpTo (steps w ts) 6).flatMap fun p=>(List.range 12).flatMap fun i=> (defects w).map fun d=>⟨a,b,role,p,i,d⟩ theorem slot_mem {r mark w} (M : MachineTable n) (s : SlotCertificate) (h : Holds r (allowed M) mark w (s.query r)) : s∈slots w (tags M) := by obtain ⟨len,walk,term⟩ := slot_route s h have a := record_in_pool (tags M) (fun _ h=>mem_tags.mpr h) _ (marked_typed h.1) have i := P455SourceFamilies.valid_slot _ term have ilt : s.terminalIndex <12 := by unfold slotStart at i; omega have pp := Problem455Finite.covered _ _ _ len (walk_steps M _ walk) simp only [slots,List.mem_flatMap,List.mem_map] exact ⟨_,a,_,bools.mem _,_,bools.mem _,_,pp,_,List.mem_range.mpr ilt,_,defect_mem _ term,rfl⟩ def directions : Cover Dir := ⟨[.right,.left,.down,.up],fun d=>by cases d <;> simp⟩ def functionalities (w : List Nat) (ts : List Tag) : List FunctionalityCertificate := let nodes:=pool w ts nodes.flatMap fun a=>bools.list.flatMap fun bit=>nodes.flatMap fun b=>nodes.flatMap fun c=> directions.list.flatMap fun d=>bools.list.map fun role=>⟨a,bit,b,c,d,role⟩ theorem func_mem {r mark w} (M : MachineTable n) (f : FunctionalityCertificate) (ok : Holds r (allowed M) mark w (f.query (system n))) : f∈functionalities w (tags M) := by obtain ⟨a,b,c⟩ := bounded_functionality (tags M) (fun _ h=>mem_tags.mpr h) _ ok simp only [functionalities,List.mem_flatMap,List.mem_map] exact ⟨_,a,_,bools.mem _,_,b,_,c,_,directions.mem _,_,bools.mem _,rfl⟩ def guards (w : List Nat) (ts : List Tag) : List Guard := (slots w ts).map .slot ++ (functionalities w ts).map .func instance pairD (a b : Nat) : DecidableRel (P455SlotProduct.pairMark a b) := by intro x y; unfold P455SlotProduct.pairMark; infer_instance def guardOK {r} (hr : 0 exact statSlot r s | func f => exact statFunc n f) infer_instance · intro g h cases g with | slot s => exact List.mem_append_left _ (List.mem_map_of_mem (slot_mem M s h.2.2.2)) | func f => exact List.mem_append_right _ (List.mem_map_of_mem (func_mem M f h.2.2.2)) def sigmaCover (s : Cover α) (b : α→Type) (t : (i : α)→Cover (b i)) : Cover (Sigma b) := ⟨s.list.flatMap (fun i => (t i).list.map (Sigma.mk i)),fun ⟨i,v⟩ => List.mem_flatMap.mpr ⟨i,s.mem _,List.mem_map_of_mem ((t i).mem v)⟩⟩ abbrev GuardKey (r : Nat) := (k : Bool) × (Fin (words r k).length × Fin (width k) × Fin (width k)) def guard {r} (hr : 0 by let w:=(words r key.1).get key.2.1 letI := capD r w; letI := guardOK hr M w key.1 key.2.2.1 key.2.2.2 unfold p; dsimp only; infer_instance let keys : Cover (GuardKey r) := sigmaCover bools _ (fun k => pairCover (fins _) (pairCover (fins _) (fins (width k)))) (coverSub keys p).map (fun c=>⟨c.val.1,c.val.2.1,c.val.2.2.1,c.val.2.2.2,c.property.1,c.property.2⟩) (fun ⟨k,i,a,b,cp,ok⟩=>⟨⟨⟨k,i,a,b⟩,cp,ok⟩,rfl⟩) end P455Enum end /- Begin Problem455FiniteBasis (from finite-semigroup-identity-bases). -/ section /- Conversion from bounded equational rank to a finite ordinary semigroup basis. Rule terms and every substitution term are nonempty. -/ namespace P455FiniteBasis open P455FirstRewrite P455FiniteModel abbrev W := List Nat def Limited (k : Nat) (w : W) := ∀ x∈w, x (u,v)∈rules) u v private theorem agree {S : Type} (M : Model S) (w : W) (f g : Nat → S) (h : ∀ x∈w, f x=g x) : M.eval f w=M.eval g w := by induction w with | nil => rfl | cons a w ih => simp only [Model.eval,h a List.mem_cons_self,ih (fun x m => h x (List.mem_cons_of_mem a m))] def table {S : Type} (M : Model S) (k : Nat) (w : W) (v : Fin k → S) := M.eval (fun x => if h : x by simp [l x m,g]) exact (read u lu).symm.trans ((congrFun eq g).trans (read v lv)) private theorem representatives {S : Type} (M : Model S) (finite : Covered S) (k : Nat) : ∃ xs : List W, (∀ z∈xs, z≠[] ∧ Limited k z) ∧ ∀ w, w≠[] → Limited k w → ∃ z∈xs, M.Valid w z := by classical have vals : Covered (Fin k → S) := pi (fin k) (fun _ => finite) (fun _ => M.unit) obtain ⟨ts,cover⟩ := pi vals (fun _ => finite) (fun _ => M.unit) let realized (t : (Fin k → S) → S) := ∃ w : W, w≠[] ∧ Limited k w ∧ table M k w=t let pick (t : (Fin k → S) → S) := if h : realized t then [Classical.choose h] else [] refine ⟨ts.flatMap pick,?_,?_⟩ · intro z m obtain ⟨t,_,hit⟩ := List.mem_flatMap.mp m by_cases h : realized t · obtain rfl : z=Classical.choose h := by simpa [pick,h] using hit exact ⟨(Classical.choose_spec h).1,(Classical.choose_spec h).2.1⟩ · simp [pick,h] at hit · intro w ne lim let t := table M k w have h : realized t := ⟨w,ne,lim,rfl⟩ obtain ⟨_,lz,ez⟩ := Classical.choose_spec h exact ⟨Classical.choose h,List.mem_flatMap.mpr ⟨t,cover t,by simp [pick,h]⟩, table_valid M lim lz ez.symm⟩ private theorem use_rule {rules : List (W×W)} {u v : W} (m : (u,v)∈rules) (a : u≠[]) (b : v≠[]) : Step (fun p q => (p,q)∈rules) u v := ⟨u,v,[],[],fun i => [i],.inl m,a,b,by simp,by simp,by simp⟩ /-- A single finite list proves every valid identity on the first k names. -/ theorem finite_fragment {S : Type} (M : Model S) (finite : Covered S) (k : Nat) : ∃ rules : List (W×W), (∀ u v, (u,v)∈rules → u≠[] ∧ v≠[] ∧ M.Valid u v) ∧ ∀ u v, u≠[] → v≠[] → Limited k u → Limited k v → M.Valid u v → Derives (fun a b => (a,b)∈rules) u v := by classical obtain ⟨reps,formed,rep⟩ := representatives M finite k let left := (List.range k).flatMap (fun x => ([]::reps).map (List.cons x)) let raw := left.flatMap (fun w => reps.map (fun z => (w,z))) let rules := raw.filter (fun p => decide (p.1≠[] ∧ p.2≠[] ∧ M.Valid p.1 p.2)) have ready (x : Nat) (lt : x (a,b)∈rules) (x::q) z := by have ne := (formed _ inR).1 apply use_rule _ (by simp) ne apply List.mem_filter.mpr refine ⟨List.mem_flatMap.mpr ⟨x::q,?_,List.mem_map.mpr ⟨z,inR,rfl⟩⟩,?_⟩ · exact List.mem_flatMap.mpr ⟨x,List.mem_range.mpr lt,List.mem_map_of_mem part⟩ · simpa using And.intro ne idn have norm (w : W) (ne : w≠[]) (lim : Limited k w) : ∀ z∈reps, M.Valid w z → Derives (fun a b => (a,b)∈rules) w z := by induction w with | nil => contradiction | cons x xs ih => intro z inR idn have lt := lim _ List.mem_cons_self by_cases empty : xs=[] · subst xs; exact .snoc (.refl _) (ready _ lt [] z List.mem_cons_self inR idn) have tail : Limited k xs := fun j m => lim j (List.mem_cons_of_mem x m) obtain ⟨q,m,valid⟩ := rep xs empty tail have chain := P455Prefix.context_derives [x] [] (ih empty tail q m valid) have last : M.Valid (x::q) z := fun f => (congrArg (M.op (f x)) (valid f).symm).trans (idn f) exact .snoc (by simpa using chain) (ready _ lt q z (List.mem_cons_of_mem _ m) inR last) refine ⟨rules,fun u v m => (of_decide_eq_true (List.mem_filter.mp m).2),?_⟩ intro u v un vn lu lv idn obtain ⟨z,zr,correct⟩ := rep u un lu have U := norm u un lu z zr correct have V := norm v vn lv z zr (fun f => (idn f).symm.trans (correct f)) exact U.trans (V.symm (fun step => P455ReductionBoundary.sym_step step)) private theorem map_eval {S : Type} (M : Model S) (d : Nat → Nat) (w : W) (f : Nat → S) : M.eval f (w.map d) = M.eval (fun a => f (d a)) w := by induction w with | nil => rfl | cons a w ih => simp [Model.eval,ih] theorem finite_rank {S : Type} (M : Model S) (finite : Covered S) (k : Nat) : ∃ rules : List (W×W), (∀ u v, (u,v)∈rules → u≠[] ∧ v≠[] ∧ M.Valid u v) ∧ ∀ u v, u≠[] → v≠[] → rank u v≤k → M.Valid u v → Derives (fun a b => (a,b)∈rules) u v := by obtain ⟨rules,ok,proof⟩ := finite_fragment M finite k refine ⟨rules,ok,?_⟩ intro u v un vn rk idn let keep := names (u++v) have ku : ∀ x∈u, x∈keep := fun x h => by simp [keep,h] have kv : ∀ x∈v, x∈keep := fun x h => by simp [keep,h] have lim (w : W) (sur : ∀ x∈w,x∈keep) : Limited k (w.map keep.idxOf) := by intro z mz; obtain ⟨x,m,rfl⟩ := List.mem_map.mp mz exact Nat.lt_of_lt_of_le (List.idxOf_lt_length_of_mem (sur x m)) rk have small := proof (u.map keep.idxOf) (v.map keep.idxOf) (by simpa using un) (by simpa using vn) (lim u ku) (lim v kv) (fun f => (map_eval M _ _ _).trans ((idn _).trans (map_eval M _ _ _).symm)) let sub (i : Nat) := [P455DefectRename.decode keep i] have restored := P455Prefix.substitute_deduction sub (by simp [sub]) small have flat (w : W) : w.flatMap sub = w.map (P455DefectRename.decode keep) := by induction w with | nil => rfl | cons x w ih => simp [List.flatMap_cons,sub] at *; exact ih simpa only [flat,P455DefectRename.decode_map ku,P455DefectRename.decode_map kv] using restored /-- A uniform bound on rank in ordinary semigroup deductions yields a finite basis; its converse is valid for every model. -/ theorem finite_of_uniform {S : Type} (M : Model S) (finite : Covered S) (k : Nat) (uniform : ∀ u v, u≠[] → v≠[] → M.Valid u v → Derives (fun a b => M.Valid a b ∧ rank a b≤k) u v) : ∃ rules, Basis M rules := by obtain ⟨rules,ok,all⟩ := finite_rank M finite k refine ⟨rules,ok,?_⟩ intro u v un vn idn have path := uniform u v un vn idn induction path with | refl => exact .refl _ | @snoc v w prev step ih => obtain ⟨a,b,l,t,h,rule,an,bn,non,rfl,rfl⟩ := step have rule' : M.Valid a b ∧ rank a b≤k := by rcases rule with fw|rev · exact fw · exact ⟨fun f => (rev.1 f).symm,(rank_swap b a).symm ▸ rev.2⟩ have localProof := all a b an bn rule'.2 rule'.1 have localStep := P455Prefix.context_derives l t (P455Prefix.substitute_deduction h non localProof) have prior := M.derives_sound (fun a b (r : M.Valid a b ∧ rank a b≤k) => r.1) prev have startN : l++a.flatMap h++t≠[] := by intro e have flat : a.flatMap h=[] := by simpa using (List.append_eq_nil_iff.mp (List.append_eq_nil_iff.mp e).1).2 obtain ⟨x,hx⟩ := List.exists_mem_of_ne_nil _ an exact non x ((List.flatMap_eq_nil_iff.mp flat) x hx) exact (ih startN prior).trans localStep end P455FiniteBasis end /- Begin Problem455PrefixTriple (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455FirstRewrite P455Quotient P455Witness P455BlockSeparators open Problem455.Slots open Problem455Swap (Link) open P455DefectProjection (select_count select_cap) theorem next_after_link {r a b : Nat} {w t : Word} (cap : Cap r w) (link : Link r w a b) (m : t ∈ rows a w) : t.tail.head? = some b := by rw [link_rows cap link] at m obtain ⟨row,mem,rfl⟩ := List.mem_map.mp m exact row_head mem theorem link_project {r a b : Nat} {w : Word} (cap : Cap r w) (link : Link r w a b) (keep : Word) (ha : a ∈ keep) (hb : b ∈ keep) : Link r (select keep w) a b := by have ct := (link_counts cap link).1 apply (all_next a b ?_).trans ((select_count keep w a ha).trans ct) intro t m rw [project_rows keep ha] at m obtain ⟨s,hm,et⟩ := List.mem_map.mp m rw [← et] have one := row_head hm have two := next_after_link cap link hm cases s with | nil => simp at one | cons x s => obtain rfl : x = a := Option.some.inj one cases s with | nil => simp at two | cons y s => obtain rfl : y = b := Option.some.inj two simp [select,ha,hb] /-- A literal successor condition can be reconstructed from every triple projection by retaining the actual next name, even when it is an outsider. -/ theorem link_of_triples {r a b : Nat} {w : Word} (cap : Cap r w) (ca : w.count a = r) (triples : ∀ z, Link r (select [a,b,z] w) a b) : Link r w a b := by apply (all_next a b ?_).trans ca intro t m have first := row_head m have each (z : Nat) : (select [a,b,z] t).tail.head? = some b := by apply next_after_link (select_cap _ cap) (triples z) rw [project_rows _ (by simp : a ∈ [a,b,z])] exact List.mem_map.mpr ⟨t,m,rfl⟩ cases t with | nil => simp at first | cons x t => have eq : x = a := Option.some.inj first subst x cases t with | nil => simpa [select] using each a | cons z s => simpa [select] using each z private theorem one_witness {r a b : Nat} {u v : Word} (cu : Cap r u) (cv : Cap r v) (counts : u.count a = v.count a) (left : Link r u a b) (right : ¬ Link r v a b) : ∃ z, Link r (select [a,b,z] u) a b ∧ ¬ Link r (select [a,b,z] v) a b := by classical have miss : ∃ z, ¬ Link r (select [a,b,z] v) a b := by apply Classical.byContradiction; intro fail exact right (link_of_triples cv (counts.symm.trans (link_counts cu left).1) (fun z => Classical.byContradiction (fun bad => fail ⟨z,bad⟩))) obtain ⟨z,m⟩ := miss exact ⟨z,link_project cu left _ (by simp) (by simp),m⟩ /-- Any obstruction returned by contraction is already seen in opposite projections to at most three input names. The order and direction of the repeated bigram are the same in these comparisons. -/ theorem asymmetric_triple {r allow ts} {u v : Word} (cu : Cap r u) (cv : Cap r v) (valid : (P455FullSingleton.model r allow ts).Valid u v) (asym : Asymmetric r u v) : ∃ a b z, (Link r (select [a,b,z] u) a b ∧ ¬ Link r (select [a,b,z] v) a b) ∨ (Link r (select [a,b,z] v) a b ∧ ¬ Link r (select [a,b,z] u) a b) := by have rule := P455FirstTesters.tester_rule (P455FirstTesters.valid_left _ _ valid) have c (a) : u.count a = v.count a := by have := rule.unary a; have := cu a; have := cv a; omega obtain ⟨a,b,e⟩ := asym rcases e with ⟨l,j⟩|⟨l,j⟩ · obtain ⟨z,h⟩ := one_witness cu cv (c a) l j; exact ⟨a,b,z,.inl h⟩ · obtain ⟨z,h⟩ := one_witness cv cu (c a).symm l j; exact ⟨a,b,z,.inr h⟩ end P455Prefix end /- Begin Problem455ChangedEvents (from finite-semigroup-identity-bases). -/ section /- From a genuine capped identity to the order of its indexed positions. Only matching of the changed *names* is needed by the final lemma. -/ namespace P455ChangedEvents open P455Witness P455Paths P455Alignment P455ContactReflection Problem455.Slots abbrev W := List Nat theorem stamped_perm {u v : W} (p : u.Perm v) (n : Nat → Nat) : (stamp n u).Perm (stamp n v) := by induction p generalizing n with | nil => exact .nil | cons a _ ih => exact .cons _ (ih _) | trans _ _ ih jh => exact (ih n).trans (jh n) | swap a b t => by_cases eq : a=b · subst b; exact .refl _ have oa : advance n [b] a=n a := by simp [advance,eq,Ne.symm eq] have ob : advance n [a] b=n b := by simp [advance,eq,Ne.symm eq] have tail : advance (advance n [a]) [b]=advance (advance n [b]) [a] := by funext z; simp only [advance]; omega simp only [stamp,oa,ob,tail] exact .swap _ _ _ private theorem earlier_idx {α : Type} [DecidableEq α] (x y : α) (w : List α) (nd : w.Nodup) (pat : [x,y].Sublist w) : w.idxOf x < w.idxOf y := by induction w with | nil => cases pat | cons b w ih => obtain ⟨fresh,rest⟩ := List.nodup_cons.mp nd cases pat with | cons _ h => have bx : b≠x := fun e => fresh (e ▸ h.subset (by simp)) have by' : b≠y := fun e => fresh (e ▸ h.subset (by simp)) simpa only [List.idxOf_cons,cond_eq_if,beq_iff_eq,if_neg bx,if_neg by', if_neg (Ne.symm bx),if_neg (Ne.symm by'),Nat.add_lt_add_iff_right] using ih rest h | cons_cons _ h => have xy : x≠y := fun e => fresh (e ▸ h.subset List.mem_cons_self) simp [List.idxOf_cons,cond_eq_if,beq_iff_eq,xy,Ne.symm xy] private theorem impossible {w : W} {x y : Event} (h : sees w [x,y]) (g : sees w [y,x]) : False := Nat.lt_asymm (earlier_idx _ _ _ (stamp_unique _ _) h) (earlier_idx _ _ _ (stamp_unique _ _) g) private theorem count_tag {a b z : Nat} (ne : a≠b) (which : z=a ∨ z=b) (tag : Tag) : (tag.flatMap (pair a b)).count z=tag.length := by induction tag with | nil => simp | cons bit t ih => cases bit <;> rcases which with rfl|rfl <;> simp [pair,List.flatMap_cons,List.count_cons,ih,ne,Ne.symm ne,Nat.add_comm] private theorem prefix_count {a b z : Nat} (ne : a≠b) (which : z=a ∨ z=b) (tag : Tag) : (profilePrefix a b tag).count z=14+tag.length := by have tt := count_tag ne which tag rcases which with rfl|rfl <;> simp [profilePrefix,List.replicate_succ,List.count_cons,ne,Ne.symm ne,tt] <;> omega private def profileMove {a b : Nat} (ne : a≠b) (tag : Tag) : Move (14+tag.length) where pre := profilePrefix a b tag p := [a] q := [b] post := [a,b] dp := by simp dq := by simp disjoint := by simpa using ne indexP := by intro z hz; exact prefix_count ne (.inl (List.mem_singleton.mp hz)) tag indexQ := by intro z hz; exact prefix_count ne (.inr (List.mem_singleton.mp hz)) tag private theorem same_if_missing {a b : Nat} (ne : a≠b) (tag : Tag) (bit : Bool) (pat : List Event) (missing : (a,14+tag.length) ∉ pat ∨ (b,14+tag.length) ∉ pat) : sees (profile a b tag bit) pat ↔ sees (profile a b tag (!bit)) pat := by let m := profileMove ne tag have flat : sees (before m) pat ↔ sees (after m) pat := sees_invariant m pat (by simpa [m,profileMove] using missing) cases bit · exact flat · exact flat.symm private theorem one_name {u : W} (a : Nat) : select [a,a] u=List.replicate (u.count a) a := by induction u with | nil => rfl | cons b t ih => by_cases e : a=b · subst b; simpa [select,List.count_cons,List.replicate_succ] using congrArg (List.cons a) ih · simpa [select,List.count_cons,e,Ne.symm e,beq_iff_eq] using ih def ChangedPair (u v : W) (x y : Nat) := select [x,y] u ≠ select [x,y] v /-- Every inverted comparison in arbitrary capped endpoints is precisely a comparison of the two mutable indexed copies in a changed binary profile. -/ theorem inverted_indices {r allow ts u v} (cap : P455Closure.Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (x y : Event) (cross : Inverted (events u) (events v) x y) : x.1 ≠ y.1 ∧ ChangedPair u v x.1 y.1 ∧ x.2=r-2 ∧ y.2=r-2 := by let ks := [x.1,y.1] have obs := sees_select ks u [x,y] (by simp [ks]) cross.1 have rev := sees_select ks v [y,x] (by simp [ks]) cross.2 have diff : select ks u ≠ select ks v := by intro eq; exact impossible (eq ▸ obs) rev have names : x.1≠y.1 := by intro eq have e : select [x.1,y.1] u = select [x.1,y.1] v := by rw [← eq,one_name,one_name,P455CellClassBinary.exact_counts cap valid] exact diff e obtain ⟨a,b,tag,bit,roles,len,_,U,V⟩ := P455CellClassBinary.changed cap valid names diff have ab : a≠b := by rcases roles with ⟨h,j⟩|⟨h,j⟩ <;> rw [h,j] <;> first | exact names | exact Ne.symm names change sees (select [x.1,y.1] u) [x,y] at obs change sees (select [x.1,y.1] v) [y,x] at rev rw [U] at obs; rw [V] at rev have necessary : (a,14+tag.length) ∈ [x,y] ∧ (b,14+tag.length) ∈ [x,y] := by constructor <;> apply Classical.byContradiction <;> intro missing · exact impossible ((same_if_missing ab tag bit _ (.inl missing)).mp obs) rev · exact impossible ((same_if_missing ab tag bit _ (.inr missing)).mp obs) rev obtain ⟨ax,bx⟩ := necessary simp only [List.mem_cons,List.not_mem_nil,or_false] at ax bx refine ⟨names,diff,?_⟩ rcases ax with e|e <;> rcases bx with f|f · exact False.elim (ab (congrArg Prod.fst (e.trans f.symm))) · rw [← e,← f]; simp only; omega · rw [← f,← e]; simp only; omega · exact False.elim (ab (congrArg Prod.fst (e.trans f.symm))) def Mates (u v : W) (r : Nat) (x y : Event) := ChangedPair u v x.1 y.1 ∧ x.2=r-2 ∧ y.2=r-2 theorem blocks_of_matching {r allow ts u v} (cap : P455Closure.Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (matching : ∀ a b c, ChangedPair u v a b → ChangedPair u v a c → b=c) : Blocks (Mates u v r) (events u) (events v) := by have cnt := P455CellClassBinary.exact_counts cap valid refine align (Mates u v r) ?_ ?_ (events u) (events v) (stamp_unique _ _) (stamped_perm (List.perm_iff_count.mpr cnt) _) ?_ · intro x y h refine ⟨?_,h.2.2,h.2.1⟩ unfold ChangedPair at * simpa only [ChangedPair,select_pair_symm x.1 y.1] using h.1 · intro x y z h k exact Prod.ext (matching _ _ _ h.1 k.1) (h.2.2.trans k.2.2.symm) · intro x y i; exact (inverted_indices cap valid x y i).2 end P455ChangedEvents end /- Begin Problem455CellClassFrames (from finite-semigroup-identity-bases). -/ section /- Fixed phase tokens may occur amid unrestricted fillers. This reconstructs literal singleton frames and simultaneous paths to arbitrary bit assignments. -/ namespace P455CellClassFrames open P455FirstRewrite P455RectangleRank P455Closure P455ConstantLayout P455CrossedSupport open P455Witness P455Uncrossed P455SlotSaturation Problem455.Slots abbrev W := List Nat def token (x y : Nat) (b : Bool) := if b then y else x def phase (x y : Nat) (tag : Tag) := (fixedPhases tag).map (token x y) private theorem extract_head {x : Nat} {xs w : W} (trace : (x::xs).Sublist w) : ∃ L K : W, w = L ++ x::K ∧ xs.Sublist K := by obtain ⟨a,b,rfl,inA,sub⟩ := List.cons_sublist_iff.mp trace obtain ⟨p,q,rfl⟩ := List.append_of_mem inA exact ⟨p,q++b,by simp [List.append_assoc],sub.trans (List.sublist_append_right q b)⟩ private theorem flat_eq {α β : Type} {xs : List α} {f g : α → List β} (eq : ∀ a ∈ xs, f a = g a) : xs.flatMap f = xs.flatMap g := congrArg List.flatten (List.map_congr_left eq) private def spelling (x y : Nat) (es : List (W × Bool)) : W := es.flatMap (fun e => e.1 ++ [token x y e.2]) private theorem interstices (x y : Nat) (bits : List Bool) (w : W) (trace : (bits.map (token x y)).Sublist w) : ∃ es K, es.map Prod.snd = bits ∧ w = spelling x y es ++ K := by induction bits generalizing w with | nil => exact ⟨[],w,rfl,rfl⟩ | cons b bs ih => obtain ⟨l,d,rfl,sub⟩ := extract_head trace obtain ⟨es,k,order,rfl⟩ := ih d sub exact ⟨(l,b)::es,k,by simp [order],by simp [spelling,List.flatMap_cons,List.append_assoc]⟩ def displayed (l : W) (x y : Nat) (m z : W) (c : Bool) := l ++ P455Structural.early x y ++ m ++ Problem455.Slots.pair x y c ++ z theorem typed_from_phases {r allow} {x y : Nat} (ne : x ≠ y) (tag : Tag) (tl : tag.length+16=r) (allowed : allow tag) (l m z : W) (middle : (phase x y tag).Sublist m) (finalPair : [x,y].Sublist z) (cap : Cap r (displayed l x y m z false)) : ∃ (f : Frame Nat) (k : W), f.tag=tag ∧ f.p=[x] ∧ f.q=[y] ∧ f.Valid r allow noMark ∧ ∀ c, displayed l x y m z c = side f l k c := by obtain ⟨es,rest,order,midEq⟩ := interstices x y (fixedPhases tag) m middle obtain ⟨p,s,hz,sub⟩ := extract_head finalPair obtain ⟨q,k,last,_⟩ := extract_head sub let f : Frame Nat := ⟨x,[],[],y,tag,es,rest,p,q⟩ have md : f.mid = spelling x y es := by unfold Frame.mid spelling apply flat_eq intro e _ cases b : e.2 <;> simp [f,Frame.p,Frame.q,token,b] have each (c : Bool) : displayed l x y m z c = side f l k c := by cases c <;> simp [displayed,side,Frame.core,md,midEq,hz,last,f,Frame.early,Frame.p,Frame.q, Frame.pair,P455Structural.early,Problem455.Slots.pair,List.append_assoc] refine ⟨f,k,rfl,rfl,rfl,?_,each⟩ apply f.valid_of_capped_shape (by change r=16+tag.length; omega) allowed order (by simp [f,Frame.p]) (by simp [f,Frame.q]) (by simp [f,Frame.p,Frame.q,ne]) (by simp [noMark]) false l k change Cap r (side f l k false) rw [← each]; exact cap theorem from_phases {r allow} {x y : Nat} (ne : x ≠ y) (tag : Tag) (tl : tag.length+16=r) (allowed : allow tag) (l m z : W) (middle : (phase x y tag).Sublist m) (finalPair : [x,y].Sublist z) (cap : Cap r (displayed l x y m z false)) : ∃ (f : Frame Nat) (k : W), f.p=[x] ∧ f.q=[y] ∧ f.Valid r allow noMark ∧ ∀ c, displayed l x y m z c = side f l k c := by obtain ⟨f,k,_,rest⟩ := typed_from_phases ne tag tl allowed l m z middle finalPair cap exact ⟨f,k,rest⟩ def revise (bits : Nat → Bool) (i : Nat) (c : Bool) (j : Nat) := if j=i then c else bits j theorem count_word (t : Nat) (middle tail : W) (bits : Nat → Bool) (x : Nat) : (word t middle tail bits).count x = (word t middle tail (constant false)).count x := by have one (i : Nat) : (mutableCell bits i).count x = (mutableCell (constant false) i).count x := by cases b : bits i <;> simp [mutableCell,constant,b,List.count_cons,Nat.add_comm] have ls (a : List Nat) : (a.flatMap (mutableCell bits)).count x = (a.flatMap (mutableCell (constant false))).count x := by induction a with | nil => rfl | cons z zs ih => simp only [List.flatMap_cons,List.count_append,ih,one] simp only [word,List.count_append,ls] theorem cap_word {r t : Nat} {middle tail : W} (zeroCap : Cap r (word t middle tail (constant false))) (bits : Nat → Bool) : Cap r (word t middle tail bits) := fun x => count_word t middle tail bits x ▸ zeroCap x theorem same_word {t : Nat} (m z : W) {s b : Nat → Bool} (agree : ∀ i i+1+v) have rr : List.range t = (lo ++ [i]) ++ hi := by conv => lhs; arg 1; rw [show t=(i+1)+(t-(i+1)) by omega] rw [List.range_add,List.range_succ] have lower : i ∉ lo := by simp [lo] have higher : i ∉ hi := by intro h; obtain ⟨v,_,eq⟩ := List.mem_map.mp h; omega let L := lo.flatMap privateCell let M := hi.flatMap privateCell ++ m ++ lo.flatMap (mutableCell bits) let Z := hi.flatMap (mutableCell bits) ++ z have fix (s : List Nat) (away : i ∉ s) (c : Bool) : s.flatMap (mutableCell (revise bits i c)) = s.flatMap (mutableCell bits) := by apply flat_eq; intro j hj have d : j ≠ i := fun e => away (e ▸ hj) simp [mutableCell,revise,d] have e (c : Bool) : word t m z (revise bits i c) = displayed L (owner i) (mate i) M Z c := by simp only [word,rr,List.flatMap_append,List.flatMap_cons,List.flatMap_nil,List.append_nil, fix lo lower,fix hi higher] cases c <;> simp [displayed,privateCell,P455Structural.early,L,M,Z,mutableCell,revise,pair,List.append_assoc] have mid := (p.tokens i ix).trans ((List.sublist_append_right (hi.flatMap privateCell) m).trans (List.sublist_append_left _ (lo.flatMap (mutableCell bits)))) have fin : [owner i,mate i].Sublist Z := (p.finalPair i ix).trans (List.sublist_append_right _ z) have cp := cap_word p.capped (revise bits i false) obtain ⟨f,k,tag,hp,hq,valid,both⟩ := typed_from_phases (by simp [owner,mate]) (p.tag i) (p.length i ix) (p.allowed i ix) L M Z mid fin (e false ▸ cp) exact ⟨f,L,k,tag,hp,hq,valid,fun c => (e c).trans (both c)⟩ theorem frameAt {r allow t m z} (p : Phases r allow t m z) (bits : Nat → Bool) {i} (ix : i show bits j = revise bits i (bits i) j by by_cases e : j=i <;> simp [revise,e])).trans (both _) have cp := cap_word p.capped bits rw [eq] at cp ⊢ refine ⟨by simp [owner,mate],p.length i ix,p.allowed i ix,bits i,?_⟩ have c := f.cross_projection valid (bits i) l k cp (owner i) (mate i) (hp ▸ List.mem_cons_self) (hq ▸ List.mem_cons_self) rw [P455SlotProduct.profile_eq,tag] at c simpa [select,side] using c theorem chain {r allow t m z} (p : Phases r allow t m z) (bits : Nat → Bool) : Chain r allow (Used t) (word t m z (constant false)) (word t m z bits) := by let active (n j : Nat) := if j simp [revise,active,same] have high : word t m z (active (i+1)) = side f l k (bits i) := by rw [← both]; apply same_word; intro j _ by_cases same : j=i · simp [revise,active,same] · have iff : j have idw : word t m z (constant false) = word t m z (active 0) := same_word m z (by simp [active,constant]) rw [idw]; exact .refl _ | succ n ih => exact (ih (by omega)).trans (step n (by omega)) have finish : word t m z (active t) = word t m z bits := same_word m z (fun i hi => by simp [active,hi]) exact finish ▸ upto t (Nat.le_refl t) end P455CellClassFrames end /- Begin Problem455CellClassRank (from finite-semigroup-identity-bases). -/ section namespace P455CellClassRank open P455FirstRewrite P455RectangleRank P455Witness P455ActualGuards P455MarkedRank open P455CellClass Problem455.Slots abbrev W := List Nat theorem no_incident_descent {r allow ts t middle tail bit i} (ix : i (P455CellClassBinary.exact_counts cap ident a) ▸ cap a have reverse : (P455FullSingleton.model r allow ts).Valid (word t middle tail bit) (word t middle tail (constant false)) := fun f => (ident f).symm exact endpoint_feasible cv (((valid_pair ..).mp ((valid_pair ..).mp reverse).2).1) (bit_change ix middle tail bit yes tailPair) /-- The witnesses are local word observations at given cell labels. No assumption about the semantic identity classes enters the padding data. The model and its entire signature are fixed before k. -/ theorem no_basis {r allow ts} (hr : 0 < r) (padding : ∀ k : Nat, ∃ (t : Nat) (middle tail : W), k < 2*t ∧ (∀ x ∈ middle ++ tail, x < 2*t) ∧ (∀ i word t middle tail (constant b))) ∧ (∀ (bit : Nat → Bool) (i : Nat), i+1 (u,v) ∈ basis) U V := by apply P455ConstantProduct.rectangle_no_basis hr _ basis sound intro k obtain ⟨t,m,z,big,small,tailPair,⟨layout⟩,next,wrap⟩ := padding k have cap : P455Quotient.Cap r (word t m z (constant false)) := by intro a; by_cases mem : a ∈ word t m z (constant false) · exact Nat.le_of_eq (layout.uniform false a mem) · simp [List.count_eq_zero.mpr mem] refine ⟨t,m,z,big,small,⟨layout⟩,(fun w idw => represent small cap tailPair idw),?_⟩ intro bit valid constructor · intro i lt yes have ix : i nodes.flatMap fun b => nodes.flatMap fun right => nodes.flatMap fun left => nodes.flatMap fun down => nodes.flatMap fun up => nodes.map fun diag => ⟨a,b,right,left,down,up,diag⟩ theorem bounded_mem {w ts} (e : EdgeCertificate) (all : ∀ v∈fields e,v∈pool w ts) : e∈certificates w ts := by simp only [certificates,List.mem_flatMap,List.mem_map] exact ⟨_,all e.a (by simp [fields]),_,all e.b (by simp [fields]),_,all e.right (by simp [fields]), _,all e.left (by simp [fields]),_,all e.down (by simp [fields]),_,all e.up (by simp [fields]), _,all e.diagonal (by simp [fields]),rfl⟩ instance markD (a b c d : Nat) : DecidableRel (marks a b c d) := by intro x y; unfold marks; infer_instance def sameNamesD (w v : List Nat) : Decidable (∀ x : Nat,x∈w ↔ x∈v) := decidable_of_iff ((∀ x∈w,x∈v) ∧ ∀ x∈v,x∈w) ⟨fun ⟨f,g⟩ x=>⟨f x,g x⟩,fun h=>⟨fun x=>(h x).1,fun x=>(h x).2⟩⟩ def edgeAccept {r} (hr : 0by letI := sameNamesD w (names (system n) e) letI := holdsD hr (allowed M) (marks a b c d) w _ (statEdge n e) unfold p; infer_instance decidable_of_iff (∃ e∈certificates w (tags M),p e) ⟨fun ⟨e,_,h⟩=>⟨e,h⟩,by rintro ⟨e,h1,h2,h3,h4,ns,h⟩ obtain ⟨k,ka,kb,eq,read,bounds⟩ := bounded_edge cp (tags M) (fun _ h=>mem_tags.mpr h) e h exact ⟨k,bounded_mem k bounds,by rw [ka,h1],by rw [ka,h2],by rw [kb,h3],by rw [kb,h4], by simpa only [eq] using ns,read⟩⟩ abbrev EdgeKey (r : Nat) := Fin (words r).length × Fin 14 × Fin 14 × Fin 14 × Fin 14 def edge {r} (hr : 0by let w:=(words r).get i letI := capD r w by_cases cp : P455Closure.Cap r w · letI := edgeAccept hr M w cp a b c d unfold p; dsimp only; infer_instance · exact .isFalse (fun h=>cp h.1) let keys : Cover (EdgeKey r) := pairCover (fins _) (pairCover (fins _) (pairCover (fins _) (pairCover (fins _) (fins _)))) (coverSub keys p).map (fun z=>⟨z.val.1,z.val.2.1,z.val.2.2.1,z.val.2.2.2.1,z.val.2.2.2.2,z.property.1,z.property.2⟩) (fun ⟨i,a,b,c,d,cp,ok⟩=>⟨⟨(i,a,b,c,d),cp,ok⟩,rfl⟩) deriving instance DecidableEq for P455GuardProduct.Index deriving instance DecidableEq for P455EdgeProduct.Index deriving instance DecidableEq for P455StructuralProduct.Index deriving instance DecidableEq for P455BinaryProduct.Index end P455Enum end /- Begin Problem455PrefixRecordLinks (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455FirstRewrite P455Quotient P455Witness P455Structural Problem455.Slots open Problem455Swap (Link) open P455DefectProjection (select_count select_cap) theorem select_swap (a b : Nat) (w : Word) : select [a,b] w = select [b,a] w := by unfold select; apply List.filter_congr; intro x _; simp [Or.comm] def PairProfile (r : Nat) (allow : Tag → Prop) (a b : Nat) (T : Word) := ∃ tag bit, tag.length+16=r ∧ allow tag ∧ (T=profile a b tag bit ∨ T=profile b a tag bit) theorem edge_iff {r allow a b w} (ab : a ≠ b) : Edge w r allow a b ↔ PairProfile r allow a b (select [a,b] w) := by constructor · rintro (⟨t,_,len,ok,bit,h⟩|⟨t,_,len,ok,bit,h⟩) · exact ⟨t,bit,len,ok,.inl h⟩ · exact ⟨t,bit,len,ok,.inr ((select_swap a b w).trans h)⟩ · rintro ⟨t,bit,len,ok,h|h⟩ · exact .inl ⟨t,ab,len,ok,bit,h⟩ · exact .inr ⟨t,ab.symm,len,ok,bit,(select_swap b a w).trans h⟩ theorem changed_edges {r allow ts u v a b} (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (ab : a ≠ b) (diff : select [a,b] u ≠ select [a,b] v) : Edge u r allow a b ∧ Edge v r allow a b := by obtain ⟨x,y,t,bit,orient,len,ok,hu,hv⟩ := P455CellClassBinary.changed cap valid ab diff rw [edge_iff ab,edge_iff ab] rcases orient with ⟨rfl,rfl⟩|⟨rfl,rfl⟩ · exact ⟨⟨t,bit,len,ok,.inl hu⟩,⟨t,!bit,len,ok,.inl hv⟩⟩ · exact ⟨⟨t,bit,len,ok,.inr hu⟩,⟨t,!bit,len,ok,.inr hv⟩⟩ theorem edge_persists {r allow ts u v a b} (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (ab : a ≠ b) (e : Edge u r allow a b) : Edge v r allow a b := by by_cases same : select [a,b] u = select [a,b] v · rw [edge_iff ab,← same]; exact (edge_iff ab).mp e · exact (changed_edges cap valid ab same).2 private theorem head_not_target {r a b z t} (cap : Cap r (z::t)) (l : Link r (z::t) a b) : z ≠ b := by intro eq; subst z have h := Problem455Swap.in_bound a (a+1) b (by omega) (b::t) rw [Problem455BlockBridge.occ_count] at h have c := (link_counts cap l).2 change Problem455Swap.bigram a b (b::t) = r at l simp [List.count_cons] at h c; omega private theorem double_not_link {r a b c t} (cap : Cap r (c::c::t)) (one : c=a ∨ c=b) : ¬ Link r (c::c::t) a b := by intro l have nb := head_not_target cap l rcases one with e|e · subst c have n := next_after_link cap l (t := a::a::t) (by simp [P455BlockSeparators.rows]) exact nb (Option.some.inj n) · exact nb e theorem profile_not_link {r allow a b T} (cap : Cap r T) (p : PairProfile r allow a b T) : ¬ Link r T a b ∧ ¬ Link r T b a := by obtain ⟨t,bit,_,_,e|e⟩ := p <;> subst T · exact ⟨double_not_link cap (.inl rfl),double_not_link cap (.inr rfl)⟩ · exact ⟨double_not_link cap (.inr rfl),double_not_link cap (.inl rfl)⟩ theorem link_fixes_binary {r allow ts a b u v} (cap : Cap r u) (ab : a ≠ b) (l : Link r u a b) (valid : (P455FullSingleton.model r allow ts).Valid u v) : select [a,b] u = select [a,b] v := by apply Classical.byContradiction; intro bad have profile := (edge_iff ab).mp (changed_edges cap valid ab bad).1 exact (profile_not_link (select_cap _ cap) profile).1 (link_project cap l _ (by simp) (by simp)) theorem not_self {r a} {u : Word} (hr : 0 < r) (cap : Cap r u) : ¬ Link r u a a := by intro l have rows := P455BlockSeparators.link_rows cap l have ct := P455BlockSeparators.rows_length a u have pos := (link_counts cap l).1 cases e : P455BlockSeparators.rows a u with | nil => simp [e] at ct; omega | cons z s => rw [e] at rows have len := congrArg List.length (List.cons.inj rows).1 simp at len theorem no_opposite {r a b} {u : Word} (hr : 0 < r) (cap : Cap r u) (l : Link r u a b) : ¬ Link r u b a := by intro back let rows := P455BlockSeparators.rows have forward := P455BlockSeparators.link_rows cap l have backward := P455BlockSeparators.link_rows cap back rw [backward,List.map_map] at forward have ct := P455BlockSeparators.rows_length a u have pos := (link_counts cap l).1 cases e : rows a u with | nil => change P455BlockSeparators.rows a u = [] at e; simp [e] at ct; omega | cons z s => change P455BlockSeparators.rows a u = z::s at e rw [e] at forward have len := congrArg List.length (List.cons.inj forward).1 simp at len; omega def exchange (a b z : Nat) := if z=a then b else if z=b then a else z private theorem shadow {a b z} (ab : a ≠ b) (az : a ≠ z) (bz : b ≠ z) (t : Word) (out : b ∉ t) : (select [a,z] (t.flatMap (openPair a b))).map (exchange a b) = select [b,z] (t.flatMap (openPair a b)) := by induction t with | nil => rfl | cons c t ih => have cb : c ≠ b := fun e => out (e ▸ List.mem_cons_self) have eq := ih (fun h => out (List.mem_cons_of_mem _ h)) simp only [List.flatMap_cons,select_append,List.map_append,eq] by_cases ca : c=a <;> by_cases cz : c=z <;> simp_all [openPair,select,exchange,Ne.symm] private theorem map_prof {r allow a b T} (d : Nat → Nat) (p : PairProfile r allow a b T) : PairProfile r allow (d a) (d b) (T.map d) := by obtain ⟨t,bit,len,ok,h|h⟩ := p <;> subst T · exact ⟨t,bit,len,ok,.inl (P455ContactReflection.map_profile ..)⟩ · exact ⟨t,bit,len,ok,.inr (P455ContactReflection.map_profile ..)⟩ theorem twin_edges {r allow a b z u} (cap : Cap r u) (l : Link r u a b) (ab : a ≠ b) (az : a ≠ z) (bz : b ≠ z) : Edge u r allow a z ↔ Edge u r allow b z := by rw [edge_iff az,edge_iff bz] let d := exchange a b have swap : (select [a,z] u).map d = select [b,z] u := by have sh := shadow ab az bz (dropName b u) (by simp) rwa [recover_link cap l] at sh have back : (select [b,z] u).map d = select [a,z] u := by rw [← swap,List.map_map] have dd : d ∘ d = id := by funext c; by_cases ca : c=a <;> by_cases cb : c=b <;> simp_all [d,exchange,Function.comp_def,Ne.symm] simp [dd] constructor · intro p; have q := map_prof d p simpa [d,exchange,ab,Ne.symm az,Ne.symm bz,← swap] using q · intro p; have q := map_prof d p simpa [d,exchange,Ne.symm ab,Ne.symm az,Ne.symm bz,← back] using q /-- A linked pair has identical binary comparisons, up to an exchange of its two names, against every distinct third name. -/ theorem linked_shadow {r a b z u} (cap : Cap r u) (l : Link r u a b) (ab : a ≠ b) (az : a ≠ z) (bz : b ≠ z) : (select [b,z] u).map (exchange a b) = select [a,z] u := by have sh := shadow ab az bz (dropName b u) (by simp) rw [recover_link cap l] at sh rw [← sh,List.map_map] have ex : exchange a b ∘ exchange a b = id := by funext c; by_cases ca : c=a <;> by_cases cb : c=b <;> simp_all [exchange,Function.comp_def,Ne.symm] simp [ex] end P455Prefix end /- Begin Problem455CellClassSnake (from finite-semigroup-identity-bases). -/ section namespace P455CellClassSnake open P455RectangleRank P455CellClassFrames P455CellClass P455Witness P455CrossedSupport open P455Closure P455SlotSaturation P455Uncrossed P455MarkedRank P455GridRows open P455PortReflection P455ActualGuards P455ConstantLayout Problem455.Slots abbrev W := List Nat theorem closedAt {r allow t m z} (p : Phases r allow t m z) (bits : Nat → Bool) {i} (ix : i by by_cases same : j=i <;> simp [revise,same]) exact ⟨f,bits i,l,k,hp,hq,ok,base.trans (both _)⟩ theorem chain_walk {r allow used u v} (cp : Cap r u) (p : Chain r allow used u v) : P455Quotient.Walk (P455Closure.Move r allow noMark) u v := by induction p with | refl => exact .refl _ | snoc _ flip ih => obtain ⟨x,y,f,b,l,k,_,_,_,yes,rfl,rfl⟩ := flip have cv : Cap r (side f l k b) := fun a => (P455Quotient.count_walk (rules r allow noMark) ih a) ▸ cp a exact .snoc ih ⟨f,b,l,k,yes,rfl,rfl,cv⟩ def At (r : Nat) (allow : Tag → Prop) (ts : Tiles) (w : W) (i j : Nat) := ∃ e : EdgeCertificate, e.a.owner=owner i ∧ e.a.mate=mate i ∧ e.b.owner=owner j ∧ e.b.mate=mate j ∧ Arrow r allow noMark w ts e private theorem free_local (ts : Tiles) (e : EdgeCertificate) : markFree (localCert ts e)=true := by have hor (a b : Node) : markFree (rightward ts a b)=true := rfl have vert (a b : Node) : markFree (downward ts a b)=true := rfl cases 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 [localCert,rr,ll,dd,uu,flagQ,allQ,markFree,hor,vert] private theorem free_succ (ts : Tiles) (e : EdgeCertificate) : markFree (chosenSuccessor ts e)=true := by cases wrap : endOfRow ts e.a && ts.bottom e.a.tag <;> simp only [chosenSuccessor,wrap,Bool.false_eq_true,if_false,if_true] <;> rfl /-- Changing the mutable cells preserves all bit-free arrows along the actual path. If a given snake edge now reads 1,0, the very same raw finite certificate succeeds with its two designated endpoint marks. -/ theorem descent {r allow ts t m z} (p : Phases r allow t m z) (bits : Nat → Bool) (finalPair : ∀ i (query_invariant mv _).mp old) have message (n : Node) (k : Nat) (lt : k word t m z (constant b)) := by have cap (b : Bool) := cap_word g.phases.capped (constant b) refine ⟨Used t,chain g.phases (constant true),?_,?_,?_,?_⟩ · intro b a ha have small := word_names _ g.names a ha have lt : a/2 first | exact eq ▸ co | exact eq ▸ cm · intro b; exact no_links hr (constant b) g.names (cap b) · rintro b _ _ ⟨i,ix,rfl,rfl⟩; exact closedAt g.phases (constant b) ix · rintro b _ _ ⟨i,ix,rfl,rfl⟩; exact g.clean b i ix theorem no_basis {r allow ts} (hr : 0 (u,v) ∈ basis) U V := by apply P455CellClassRank.no_basis hr _ basis sound intro k; obtain ⟨t,m,z,big,⟨g⟩⟩ := padding k exact ⟨t,m,z,big,g.names,g.finalPair,⟨layout hr g⟩, fun bit i h yes no => descent g.phases bit g.finalPair (by omega) h yes no (g.next i h), fun bit h yes no => descent g.phases bit g.finalPair (by omega) h yes no (g.wrap h)⟩ end P455CellClassSnake end /- Begin Problem455PrefixLinkInvariance (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455FirstRewrite P455Quotient P455Witness P455Structural Problem455.Slots open Problem455Swap (Link) open P455DefectProjection (select_cap) theorem select_valid {A : Type} (M : Model A) (keep : Word) {u v : Word} (valid : M.Valid u v) : M.Valid (select keep u) (select keep v) := by let f (x : Nat) : Word := if x ∈ keep then [x] else [] have eq (w : Word) : w.flatMap f = select keep w := by induction w with | nil => rfl | cons c t ih => by_cases k : c ∈ keep <;> simp [f,select,k,ih] intro val; rw [← eq,← eq,M.eval_instance,M.eval_instance]; exact valid _ private theorem selected_self (k w : Word) (sup : ∀ t ∈ w, t ∈ k) : select k w = w := List.filter_eq_self.mpr (fun t m => by simpa using sup t m) private theorem three_ext {a b z : Nat} {u v : Word} (su : ∀ t ∈ u, t ∈ [a,b,z]) (sv : ∀ t ∈ v, t ∈ [a,b,z]) (count : ∀ t, u.count t = v.count t) (xy : select [a,b] u = select [a,b] v) (xz : select [a,z] u = select [a,z] v) (yz : select [b,z] u = select [b,z] v) : u = v := by let g (c : Nat) : Word := if c ∈ [a,b,z] then [c] else [] have dec (w : Word) (sup : ∀ t ∈ w, t ∈ [a,b,z]) : w.flatMap g = w := by induction w with | nil => rfl | cons c t ih => have m := sup c List.mem_cons_self simpa only [List.flatMap_cons,g,if_pos m,List.singleton_append] using congrArg (List.cons c) (ih (fun d hd => sup d (List.mem_cons_of_mem _ hd))) rw [← dec u su,← dec v sv] apply trace g count intro i j bad have hi : i ∈ [a,b,z] := by apply Classical.byContradiction; intro h; exact bad (by simp only [g,if_neg h,List.nil_append,List.append_nil]) have hj : j ∈ [a,b,z] := by apply Classical.byContradiction; intro h; exact bad (by simp only [g,if_neg h,List.nil_append,List.append_nil]) have ne : i ≠ j := fun e => bad (by rw [e]) have rev {c d : Nat} (eq : select [c,d] u = select [c,d] v) : select [d,c] u = select [d,c] v := by rw [select_swap d c u,select_swap d c v,eq] have cvt (x y : Nat) (w : Word) : proj x y w = select [x,y] w := by simp [proj,select] rw [cvt,cvt] simp only [List.mem_cons,List.not_mem_nil,or_false] at hi hj rcases hi with ha|hb|hz <;> rcases hj with ka|kb|kz <;> subst i <;> subst j <;> first | contradiction | exact xy | exact xz | exact yz | exact rev xy | exact rev xz | exact rev yz theorem edge_no_links {r allow a z} {v : Word} (cv : Cap r v) (az : a ≠ z) (e : Edge v r allow a z) : ¬ Link r v a z ∧ ¬ Link r v z a := by have p := profile_not_link (select_cap [a,z] cv) ((edge_iff az).mp e) exact ⟨fun l => p.1 (link_project cv l _ (by simp) (by simp)), fun l => p.2 (link_project cv l _ (by simp) (by simp))⟩ /-- All hypotheses here are local: validity, the cap, and a three-name support. The tester is constructed from the endpoint where the directed link splits. -/ theorem triple_invariant {r allow ts a b z} {u v : Word} (hr : 0 < r) (cu : Cap r u) (cv : Cap r v) (valid : (P455FullSingleton.model r allow ts).Valid u v) (su : ∀ t ∈ u, t ∈ [a,b,z]) (sv : ∀ t ∈ v, t ∈ [a,b,z]) (left : Link r u a b) : Link r v a b := by classical apply Classical.byContradiction; intro failed have neq : u ≠ v := fun eq => failed (eq ▸ left) have ab : a ≠ b := fun eq => not_self hr cu (eq ▸ left) have fixed := link_fixes_binary cu ab left valid have third : z ≠ a ∧ z ≠ b := by have separate (hz : z ∈ [a,b]) : False := by have cut (w : Word) (sw : ∀ t ∈ w, t ∈ [a,b,z]) : select [a,b] w = w := by apply selected_self; intro t ht have mem := sw t ht simp only [List.mem_cons,List.not_mem_nil,or_false] at mem hz ⊢ rcases mem with h|h|h · exact .inl h · exact .inr h · exact h ▸ hz exact neq ((cut u su).symm.trans (fixed.trans (cut v sv))) exact ⟨fun e => separate (by simp [e]),fun e => separate (by simp [e])⟩ have az := third.1.symm have bz := third.2.symm have twins := twin_edges (allow := allow) cu left ab az bz have counts := P455CellClassBinary.exact_counts cu valid have eA : Edge u r allow a z := by by_cases eq : select [a,z] u = select [a,z] v · have other : select [b,z] u ≠ select [b,z] v := fun s => neq (three_ext su sv counts fixed eq s) exact twins.mpr (changed_edges cu valid bz other).1 · exact (changed_edges cu valid az eq).1 have va := edge_persists cu valid az eA have vb := edge_persists cu valid bz (twins.mp eA) have ea := edge_no_links cv az va have eb := edge_no_links cv bz vb have rev : ¬ Link r v b a := by intro l have h := link_project cv l [a,b] (by simp) (by simp) rw [← fixed] at h exact no_opposite hr (select_cap _ cu) (link_project cu left _ (by simp) (by simp)) h have cmp : P455SourceFamilies.Compressed r v := by intro i j link obtain ⟨ci,cj⟩ := link_counts cv link have mi := sv i (List.count_pos_iff.mp (ci ▸ hr)) have mj := sv j (List.count_pos_iff.mp (cj ▸ hr)) simp only [List.mem_cons,List.not_mem_nil,or_false] at mi mj rcases mi with hi|hi|hi <;> rcases mj with hj|hj|hj <;> subst i <;> subst j <;> first | exact not_self hr cv link | exact failed link | exact rev link | exact ea.1 link | exact ea.2 link | exact eb.1 link | exact eb.2 link have structural : Structural v r allow := .inl ⟨⟨[a,b,z],by simp,sv⟩,z,a,b,third.1,third.2,ab, va.elim Or.inr Or.inl,vb.elim Or.inr Or.inl⟩ have fixedV := selected_self [a,b,z] v sv have eq := P455StructuralReflection.literal_projection hr cv (fun f => (valid f).symm) [a,b,z] (by simp) (by simpa only [fixedV] using structural) (by simpa only [fixedV] using cmp) exact neq (by simpa only [fixedV,selected_self [a,b,z] u su] using eq.symm) /-- The directed repeated links of the two sides of any capped valid identity in the full tester product agree. -/ theorem identity_link {r allow ts} (hr : 0 < r) {u v : Word} (cu : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (a b : Nat) : Link r u a b ↔ Link r v a b := by have counts := P455CellClassBinary.exact_counts cu valid have cv : Cap r v := fun i => counts i ▸ cu i have go {U V : Word} (cU : Cap r U) (cV : Cap r V) (ct : U.count a = V.count a) (idUV : (P455FullSingleton.model r allow ts).Valid U V) (l : Link r U a b) : Link r V a b := by apply link_of_triples cV (ct.symm.trans (link_counts cU l).1) intro z let k := [a,b,z] have cover (w : Word) (t : Nat) (h : t ∈ select k w) : t ∈ k := by simpa only [decide_eq_true_eq] using (List.mem_filter.mp h).2 exact triple_invariant hr (select_cap _ cU) (select_cap _ cV) (select_valid _ k idUV) (cover U) (cover V) (link_project cU l k (by simp [k]) (by simp [k])) exact ⟨go cu cv (counts a) valid,go cv cu (counts a).symm (fun f => (valid f).symm)⟩ /-- Any capped valid identity is a single shared nonempty substitution of a capped, compressed valid identity; no link-preservation hypothesis. -/ theorem compressed_instance {r allow ts} (hr : 0 < r) (u v : Word) (cu : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) : ∃ A B : Word, ∃ h : Nat → Word, (∀ z, h z ≠ []) ∧ A.flatMap h = u ∧ B.flatMap h = v ∧ Cap r A ∧ Cap r B ∧ (P455FullSingleton.model r allow ts).Valid A B ∧ P455SourceFamilies.Compressed r A ∧ P455SourceFamilies.Compressed r B := by have cv : Cap r v := fun i => P455CellClassBinary.exact_counts cu valid i ▸ cu i obtain ⟨A,B,h,n,e,f,ca,cb,ok,_,outcome⟩ := contract_common hr u v cu cv valid refine ⟨A,B,h,n,e,f,ca,cb,ok,?_⟩ rcases outcome with done|⟨a,b,⟨l,miss⟩|⟨l,miss⟩⟩ · exact done · exact (miss ((identity_link hr ca ok a b).mp l)).elim · exact (miss ((identity_link hr ca ok a b).mpr l)).elim end P455Prefix end /- Begin Problem455CellClassClean (from finite-semigroup-identity-bases). -/ section namespace P455CellClassClean open P455RectangleRank P455CellClass P455CellClassFrames P455CellClassSnake open P455Witness P455GridRows P455PortReflection P455SlotSaturation P455SingletonEvaluation open P455CrossedSupport P455Paths P455TerminalTransfer P455ConstantLayout Problem455.Slots abbrev W := List Nat def SmallSlots (U : W) := ∀ o ∈ U, ∀ k, slotStart k → ∃ S : W, S.length ≤ 4 ∧ ∀ x, occupies U o k x → x ∈ S def Ports (r : Nat) (allow : Tag → Prop) (ts : Tiles) (U : W) := ∀ n : Node, Holds r allow noMark U (typedNode n) → Functional r allow noMark U ts n theorem packed_counts {r allow t m z} (p : Phases r allow t m z) (names : ∀ x ∈ m++z,x<2*t) (bits : Nat → Bool) (a : Nat) (mem : a ∈ word t m z bits) : (word t m z bits).count a=r := by have small := word_names _ names _ mem obtain ⟨_,co,cm,_⟩ := flip_counts (cap_word p.capped bits) (closedAt p bits (show a/2 first | exact eq ▸ co | exact eq ▸ cm theorem record_roles {r allow mark t m z} (bits : Nat → Bool) (names : ∀ x ∈ m++z,x<2*t) (finalPair : ∀ i bad (Or.inl e),fun e => bad (Or.inr e)⟩ exact forb (.inl ⟨n.tag,ne,len,tag,bit,pr⟩) rcases own with one|one <;> rcases mat with two|two · exact False.elim (ne (one.trans two.symm)) · exact ⟨i,ix,one,two⟩ · rw [one,two,select_pair_symm (owner i) (mate i)] at pr have last := congrArg List.getLast? pr simp [word,select_append,finalPair i ix,profile,List.getLast?_append] at last unfold owner mate at last; omega · exact False.elim (ne (one.trans two.symm)) theorem all_bits {r allow mark t m z} (c value : Bool) (names : ∀ x ∈ m++z,x<2*t) (finalPair : ∀ i cases c <;> simp_all [constant,profile,pair] private theorem slot_false {r allow mark t m z} (p : Phases r allow t m z) (names : ∀ x ∈ m++z,x<2*t) (size : SmallSlots (word t m z (constant false))) (s : SlotCertificate) (b : Bool) (obs : Holds r allow mark (word t m z (constant b)) (s.query r)) : False := by obtain ⟨_,_,term⟩ := slot_route s obs let w := word t m z (constant b) let zero := word t m z (constant false) let o := endpoint (if s.startAtMate then s.anchor.mate else s.anchor.owner) s.steps change Holds r allow mark w (terminalSlot r o s.terminalIndex s.defect) at term let q := terminalSlot r o s.terminalIndex s.defect have atW : Holds r allow noMark w q := remark (P455GuardProduct.free_term ..) term have walk := chain_walk p.capped (chain p (constant b)) have back : P455Quotient.Walk (P455Closure.Move r allow noMark) w zero := walk.symm (fun mv => mv.symm) have atZ := back.transport atW (fun mv h => (query_invariant mv _).mp h) change Holds r allow noMark zero (terminalSlot r o s.terminalIndex s.defect) at atZ cases d : s.defect with | deficient a => rw [d] at atZ obtain ⟨⟨_,j,events⟩,under⟩ := atZ have mem := stamped_mem_label _ _ (a,j) (events.subset (by simp)) have ct := packed_counts p names (constant false) a mem change zero.count a < r at under change zero.count a = r at ct omega | overflow xs => rw [d] at atZ obtain ⟨count,sep,all,_⟩ := atZ change xs.length=5 at count have occupied (a : Nat) (h : a ∈ xs) : slotStart s.terminalIndex ∧ occupies zero o s.terminalIndex a := by have qh := (P455TerminalTransfer.holds_all _).mp all (.both (.count a r) (.slot o s.terminalIndex a)) (by simp [h]) exact qh.2 have someA : ∃ a, a ∈ xs := by cases xs with | nil => simp at count | cons a ys => exact ⟨a,List.mem_cons_self⟩ obtain ⟨a,ha⟩ := someA obtain ⟨slot,j,ev⟩ := occupied a ha have ownMem := stamped_mem_label _ _ (o,s.terminalIndex) (ev.subset (by simp)) obtain ⟨S,low,cover⟩ := size o ownMem s.terminalIndex slot have apart := (block_separation _).mp sep have nd : xs.Nodup := by apply (List.pairwise_cons.mp apart).2.imp_of_mem intro a b ha _ sep same subst b have req := (P455TerminalTransfer.holds_all _).mp all (.both (.count a r) (.slot o s.terminalIndex a)) (List.mem_map.mpr ⟨a,ha,rfl⟩) have ca : Problem455Swap.occ a zero = r := (Problem455BlockBridge.occ_count ..).trans req.1 exact sep ⟨ca,ca,.refl _⟩ have le := P455FirstRewrite.size_le nd (fun x hx => cover _ (occupied _ hx).2) omega theorem clean {r allow ts t m z} (p : Phases r allow t m z) (names : ∀ x ∈ m++z,x<2*t) (finalPair : ∀ i exact slot_false p names small s bit read | functionality f => obtain ⟨marked,nb,nc,different,_⟩ := read have atB := neighbor_remark (dst := noMark) nb have atC := neighbor_remark (dst := noMark) nc have recProof : Holds r allow noMark (word t m z (constant bit)) (typedNode f.anchor) := ⟨marked.1,marked.2.1,marked.2.2.1,f.bit,marked.2.2.2.2⟩ have walk := (chain_walk p.capped (chain p (constant bit))).symm (fun mv => mv.symm) have back (q : Query) (h : Holds r allow noMark (word t m z (constant bit)) q) : Holds r allow noMark (word t m z (constant false)) q := walk.transport h (fun mv old => (query_invariant mv _).mp old) have eq := ports f.anchor (back _ recProof) f.dir f.b f.c (back _ atB) (back _ atC) change ¬ Problem455Swap.SameBlock r _ _ _ at different rw [eq] at different obtain ⟨ca,cb⟩ := record_counts (cap_word p.capped (constant bit)) (neighbor_target_record atC) have occ : Problem455Swap.occ (if f.distinguishMate then f.c.mate else f.c.owner) (word t m z (constant bit)) = r := by rw [Problem455BlockBridge.occ_count] cases b : f.distinguishMate <;> simp only [b,Bool.false_eq_true,if_false,if_true] <;> assumption exact different ⟨occ,occ,.refl _⟩ | edge e => have yes := all_bits bit true names finalPair e.a read.1 have no := all_bits bit false names finalPair e.b read.2.1 cases bit <;> contradiction /-- Remaining word data are only positive geometry and literal bounds on the zero word. No identity, negative tester assertion, mixed-word evidence, layout, or normal-form hypothesis is included. -/ structure Data (r : Nat) (allow : Tag → Prop) (ts : Tiles) (t : Nat) (m z : W) where phases : Phases r allow t m z names : ∀ x ∈ m++z,x<2*t finalPair : ∀ i clean d.phases d.names d.finalPair d.small d.ports bit (owner i) (mate i),d.next,d.wrap⟩ theorem no_basis {r allow ts} (hr : 0 (u,v) ∈ basis) U V := by apply P455CellClassSnake.no_basis hr _ basis sound intro k; obtain ⟨t,m,z,g,⟨d⟩⟩ := padding k exact ⟨t,m,z,g,⟨d.geometry⟩⟩ end P455CellClassClean end /- Begin Problem455PrefixInsertion (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455Quotient P455FirstRewrite P455Witness Problem455.Slots open Problem455Swap (bigram Link hit) def beforePair (a b z : Nat) : Word := if z=b then [a,b] else [z] theorem recover_link_left {r a b} {w : Word} (hr : 0 < r) (cap : Cap r w) (l : Link r w a b) : (dropName a w).flatMap (beforePair a b) = w := by have ne : a ≠ b := fun e => not_self hr cap (e ▸ l) have restore (t : Word) (fresh : b ∉ t) : (dropName a (t.flatMap (openPair a b))).flatMap (beforePair a b) = t.flatMap (openPair a b) := by induction t with | nil => rfl | cons x t ih => have xb : x ≠ b := fun e => fresh (e ▸ List.mem_cons_self) have tail := ih (fun h => fresh (List.mem_cons_of_mem _ h)) simp only [List.flatMap_cons,dropName,List.filter_append,List.flatMap_append] at tail ⊢ rw [tail] by_cases xa : x=a <;> simp [openPair,beforePair,xa,xb,ne,Ne.symm ne] have h := restore (dropName b w) (by simp) rwa [recover_link cap l] at h /-- Every b,c boundary of the input appears between the last symbol of the b-image and first symbol of the c-image. Further occurrences only help. -/ theorem boundary_count (g : Nat → Word) (b c X Y : Nat) (last : (g b).getLast? = some X) (first : (g c).head? = some Y) (w : Word) : bigram b c w ≤ bigram X Y (w.flatMap g) := by induction w with | nil => simp [bigram] | cons j t ih => rw [List.flatMap_cons,Problem455Swap.bigram_append] change hit b c (some j) t.head? + bigram b c t ≤ _ by_cases h : j=b ∧ t.head?=some c · obtain ⟨rfl,p⟩ := h have head : (t.flatMap g).head? = some Y := by cases t with | nil => simp at p | cons x s => have xc : x=c := Option.some.inj p subst x cases e : g c with | nil => simp [e] at first | cons k ks => simpa [e] using first simp [hit,p,last,head]; omega · simp [hit,h]; omega private theorem computed_link {r b c X Y} {w v : Word} (cap : Cap r v) (g : Nat → Word) (recover : w.flatMap g = v) (edge : Link r w b c) (last : (g b).getLast? = some X) (first : (g c).head? = some Y) : Link r v X Y := by have low := boundary_count g b c X Y last first w rw [recover,show bigram b c w=r from edge] at low have top := Problem455Swap.out_bound X Y (Y+1) (by omega) v rw [Problem455BlockBridge.occ_count] at top have := cap X change bigram X Y v=r; omega /-- If deleting z repairs b→c and z itself is attached to some saturated name by a repeated directed link, it must occupy precisely b|c at every occurrence. No claim is made about any unattached outsider. -/ theorem inserted_between {r b c z} {w : Word} (hr : 0 < r) (cap : Cap r w) (after : Link r (dropName z w) b c) (split : ¬ Link r w b c) (anchored : ∃ p, Link r w p z ∨ Link r w z p) : Link r w b z ∧ Link r w z c := by obtain ⟨p,incoming|outgoing⟩ := anchored · have recover := recover_link cap incoming have head : ((openPair p z) c).head? = some c := by by_cases h : c=p <;> simp [openPair,h] have bp : b=p := by apply Classical.byContradiction; intro n exact split (computed_link cap _ recover after (by simp [openPair,n]) head) subst p exact ⟨incoming,computed_link cap _ recover after (by simp [openPair]) head⟩ · have recover := recover_link_left hr cap outgoing have last : ((beforePair z p) b).getLast? = some b := by by_cases h : b=p <;> simp [beforePair,h] have cp : c=p := by apply Classical.byContradiction; intro n exact split (computed_link cap _ recover after last (by simp [beforePair,n])) subst p exact ⟨computed_link cap _ recover after last (by simp [beforePair]),outgoing⟩ /-- Order of the first retained copies is invariant under deleting other names. -/ theorem first_select (k w : Word) {a b : Nat} (ha : a ∈ k) (hb : b ∈ k) : (select k w).idxOf a < (select k w).idxOf b ↔ w.idxOf a < w.idxOf b := by induction w with | nil => rfl | cons x w ih => by_cases xa : x=a <;> by_cases xb : x=b <;> by_cases keep : x ∈ k <;> simp_all [select,List.idxOf_cons,cond_eq_if,beq_iff_eq,Ne.symm] theorem link_first {r a b} {w : Word} (hr : 0 < r) (cap : Cap r w) (l : Link r w a b) : w.idxOf a < w.idxOf b := by let k := [a,b] have ab : a≠b := fun e => not_self hr cap (e ▸ l) obtain ⟨ca,_⟩ := link_counts cap l have keep : a ∈ k := by simp [k] have inW : a ∈ select k w := List.mem_filter.mpr ⟨List.count_pos_iff.mp (ca ▸ hr),by simpa using keep⟩ have link := link_project cap l k keep (by simp [k]) have cp := P455DefectProjection.select_cap k cap apply (first_select k w keep (by simp [k])).mp cases e : select k w with | nil => simp [e] at inW | cons x t => have m : x ∈ k := by have mem : x ∈ select k w := e ▸ List.mem_cons_self simpa only [decide_eq_true_eq] using (List.mem_filter.mp mem).2 have nb : x≠b := by intro eq; subst x rw [e] at link cp have inc := Problem455Swap.in_bound a (a+1) b (by omega) (b::t) rw [Problem455BlockBridge.occ_count] at inc have total := (link_counts cp link).2 change bigram a b (b::t)=r at link simp [List.count_cons] at inc total; omega have xa : x=a := by simpa [k,nb] using m subst x; simp [List.idxOf_cons,cond_eq_if,beq_iff_eq,ab,Ne.symm ab] end P455Prefix end /- Begin Problem455PrivatePhase (from finite-semigroup-identity-bases). -/ section namespace P455PrivatePhase open P455Witness P455Structural P455ChangedEvents P455Prefix P455DefectProjection open P455ContactReflection Problem455.Slots open Problem455Swap (Link) abbrev W := List Nat theorem edge_project {r allow u a b} (k : W) (ka : a∈k) (kb : b∈k) : Edge (select k u) r allow a b ↔ Edge u r allow a b := by have x := select_sub k [a,b] u (by simpa using And.intro ka kb) have y := select_sub k [b,a] u (by simpa using And.intro kb ka) simp only [Edge,Rec,Holds,x,y,typed] at * theorem no_intruder {r allow ts u v a b} (cap : P455Closure.Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (recProof : Rec u r allow a b) (changed : ChangedPair u v a b) (isolated : ∀ z, z≠a → z≠b → ¬ Edge u r allow a z ∧ ¬ Edge u r allow b z) (z j : Nat) (za : z≠a) (zb : z≠b) : ¬ sees u [(a,0),(z,j),(b,2)] := by intro occurs obtain ⟨tag,ab,len,tagOk,bit,prof⟩ := recProof have hr : 0 rcases ml with e|e|e <;> subst i <;> subst l <;> first | exact not_self hr capU link | exact nonAB.1 link | exact nonAB.2 link | exact nonAZ.1 link | exact nonAZ.2 link | exact nonBZ.1 link | exact nonBZ.2 link have obs := sees_select k u _ (by simp [k]) occurs have st : Structural U r allow := .inr ⟨⟨k,by simp [k],names⟩,a,b,z,j,ab,za,zb,binary,obs⟩ have eq := P455StructuralReflection.literal_projection hr cap valid k (by simp [k]) st cmp have ext := congrArg (select [a,b]) eq rw [select_sub k [a,b] u (by simp [k]),select_sub k [a,b] v (by simp [k])] at ext exact changed ext private theorem peel (k : W) {w : W} (x : Nat) (t : W) (eq : select k w=x::t) : ∃ l r, w=l++x::r ∧ select k l=[] ∧ select k r=t := by induction w with | nil => cases eq | cons a w ih => by_cases keep : a∈k · have ⟨e,tail⟩ := List.cons.inj (show a::select k w=x::t by simpa [select,keep] using eq) exact ⟨[],w,by simp [e],rfl,tail⟩ · obtain ⟨l,r,mid,el,er⟩ := ih (by simpa [select,keep] using eq) exact ⟨a::l,r,by simp [mid],by simpa [select,keep] using el,er⟩ private theorem cut (k : W) (p : W) (x : Nat) (t : W) (w : W) (eq : select k w=p++x::t) : ∃ m z, w=m++x::z ∧ select k m=p ∧ select k z=t := by induction p generalizing w with | nil => exact peel k x t eq | cons a p ih => obtain ⟨l,r,f,el,er⟩ := peel k a (p++x::t) eq have keptA : a∈k := P455DefectRename.kept (keep:=k) (w:=w) (a:=a) (by rw [eq]; simp) obtain ⟨m,z,mz,em,ez⟩ := ih r er refine ⟨l++a::m,z,?_,?_,ez⟩ · simp [f,mz,List.append_assoc] · rw [select_append,el]; simpa [select,keptA] using congrArg (List.cons a) em private theorem stamped_three (l p q t : W) (a z b : Nat) : sees (l ++ a :: (p ++ z :: (q ++ b :: t))) [(a,l.count a),(z,(l++a::p).count z),(b,(l++a::(p++z::q)).count b)] := by let n₁ := advance (fun _ => 0) l let n₂ := advance (advance n₁ [a]) p let n₃ := advance (advance n₂ [z]) q have one : n₁ a = l.count a := by simp [n₁,advance] have two : n₂ z = (l++a::p).count z := by simp [n₁,n₂,advance,List.count_cons,List.count_append,beq_iff_eq]; omega have three : n₃ b = (l++a::(p++z::q)).count b := by simp [n₁,n₂,n₃,advance,List.count_cons,List.count_append,beq_iff_eq]; omega unfold sees events rw [← one,← two,← three] simp only [stamp_append,stamp] have end' : [(b,n₃ b)].Sublist ((b,n₃ b)::stamp (advance n₃ [b]) t) := List.singleton_sublist.mpr List.mem_cons_self have qq := end'.trans (List.sublist_append_right (stamp (advance n₂ [z]) q) _) have zz := qq.cons₂ (z,n₂ z) have pp := zz.trans (List.sublist_append_right (stamp (advance n₁ [a]) p) _) exact (pp.cons₂ (a,n₁ a)).trans (List.sublist_append_right _ _) /-- Absence of the indexed intrusion is exactly strong enough to turn the first six projected positions into a literal factor of the source. -/ theorem closed_of_no_intruder {w : W} {a b : Nat} (ab : a≠b) (profileStart : ∃ t : W, select [a,b] w=P455Structural.early a b++t) (none : ∀ z j, z≠a → z≠b → ¬sees w [(a,0),(z,j),(b,2)]) : P455Structural.Closed w a b := by obtain ⟨t,eq⟩ := profileStart let k := [a,b] obtain ⟨l,r,first,l0,rest⟩ := peel k a ([a,b,a,b,b]++t) eq obtain ⟨m,z,last,middle,_⟩ := cut k [a,b,a,b] b t r rest have ca : l.count a=0 := by rw [← select_count k l a (by simp [k]),l0]; rfl have cb : l.count b=0 := by rw [← select_count k l b (by simp [k]),l0]; rfl have two : m.count b=2 := by rw [← select_count k m b (by simp [k]),middle] simp [List.count_cons,ab,Ne.symm ab] have sel : select k m=m := by apply List.filter_eq_self.mpr intro d mem by_cases da : d=a · simp [k,da] by_cases db : d=b · simp [k,db] obtain ⟨p,q,ms⟩ := List.append_of_mem mem have triple := stamped_three l p q z a d b have pos : (l++a::(p++d::q)).count b=2 := by rw [← ms]; simp [List.count_cons,ab,Ne.symm ab,cb,two] rw [ca,pos] at triple apply False.elim (none d ((l++a::p).count d) da db ?_) simpa [first,last,ms,List.append_assoc] using triple refine ⟨ab,l,z,?_,List.count_eq_zero.mp ca,List.count_eq_zero.mp cb⟩ have small := sel.symm.trans middle simp [first,last,small,P455Structural.early,List.append_assoc] theorem closed_changed {r allow ts u v a b} (cap : P455Closure.Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (recProof : Rec u r allow a b) (changed : ChangedPair u v a b) (isolated : ∀ z, z≠a → z≠b → ¬ Edge u r allow a z ∧ ¬ Edge u r allow b z) : P455Structural.Closed u a b := by have ban := no_intruder cap valid recProof changed isolated obtain ⟨tag,ab,_,_,bit,eq⟩ := recProof apply closed_of_no_intruder ab _ ban exact ⟨_,by simpa [profile,profilePrefix,P455Structural.early,List.append_assoc] using eq⟩ end P455PrivatePhase end /- Begin Problem455PrefixGlobal (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455FirstRewrite P455Quotient /-- Unconditional from validity in the fixed monoid. The original endpoints reduce by small steps to a common prefix on a common nonempty expansion of a capped, compressed valid identity. Every deduction between those compressed words yields an ordinary deduction of the original identity. -/ theorem normalized_compressed {r allow ts} (hr : 0 < r) {u v : Word} (valid : (P455FullSingleton.model r allow ts).Valid u v) : ∃ A B : Word, ∃ h : Nat → Word, (∀ z, h z ≠ []) ∧ Cap r A ∧ Cap r B ∧ P455SourceFamilies.Compressed r A ∧ P455SourceFamilies.Compressed r B ∧ (P455FullSingleton.model r allow ts).Valid A B ∧ A.flatMap h = residual (highNames r u) u ∧ B.flatMap h = residual (highNames r u) v ∧ Derives (Steps r allow ts) u (headPowers r (highNames r u) ++ A.flatMap h) ∧ Derives (Steps r allow ts) v (headPowers r (highNames r u) ++ B.flatMap h) ∧ (∀ k, Derives (fun p q => (P455FullSingleton.model r allow ts).Valid p q ∧ rank p q ≤ k) A B → Derives (fun p q => (P455FullSingleton.model r allow ts).Valid p q ∧ rank p q ≤ max k (2*(r+2)+1)) u v) := by obtain ⟨left,right,cu,_,suffixID,_⟩ := arbitrary_prefix valid obtain ⟨A,B,h,non,hu,hv,ca,cb,idAB,cmpA,cmpB⟩ := compressed_instance hr _ _ cu suffixID refine ⟨A,B,h,non,ca,cb,cmpA,cmpB,idAB,hu,hv,?_,?_,?_⟩ · rw [hu]; exact left · rw [hv]; exact right · intro k walk apply reassemble valid simpa only [hu,hv] using substitute_deduction h non walk end P455Prefix end /- Begin Problem455CellClassPadded (from finite-semigroup-identity-bases). -/ section /- Literal middle and final phases for the five grid matching lists, with independently assigned tile tags and the row-major column pass. -/ namespace P455CellClassPadded open P455CellClassFrames P455RectangleRank P455PaddedWord P455Witness P455Closure open Problem455.Slots abbrev W := List Nat private theorem part {α : Type} (f : α → W) {xs : List α} {x : α} (mem : x ∈ xs) : (f x).Sublist (xs.flatMap f) := by obtain ⟨l,k,rfl⟩ := List.append_of_mem mem simp only [List.flatMap_append,List.flatMap_cons] exact (List.sublist_append_left ..).trans (List.sublist_append_right ..) private theorem parts (s : List Nat) (f g : Nat → W) (each : ∀ i ∈ s, (f i).Sublist (g i)) : (s.flatMap f).Sublist (s.flatMap g) := by induction s with | nil => exact .refl _ | cons c cs ih => exact (each c List.mem_cons_self).append (ih (fun j h => each j (List.mem_cons_of_mem _ h))) private theorem port_sublist {bs : List P455PaddedPorts.Block} {i : Nat} (hi : i∈bs.flatMap P455PaddedPorts.cells) : (P455PaddedPorts.roles i ++ P455PaddedPorts.roles i).Sublist (P455PaddedPorts.letters bs) := by obtain ⟨block,m,inBlock⟩ := List.mem_flatMap.mp hi have v := part P455PaddedPorts.roles inBlock have piece := part (fun b => (P455PaddedPorts.cells b ++ P455PaddedPorts.cells b).flatMap P455PaddedPorts.roles) m simp only [P455PaddedPorts.letters,P455PaddedPorts.phase,List.flatMap_assoc] apply List.Sublist.trans _ piece try dsimp only rw [List.flatMap_append]; exact v.append v private theorem ports {h w i : Nat} (size : 1 exact .refl _ | succ k ih => have split : portChunks h w (k+1) = portChunks h w k ++ P455PaddedPorts.letters (matching h w k) := by simp [portChunks,List.range_succ] rw [split,List.replicate_succ',List.flatten_append]; simp only [List.flatten_cons,List.flatten_nil,List.append_nil] exact ih.append (port_sublist ((matching_cells size k i).mpr ix)) private theorem enumerate (bs : List Bool) : (List.range bs.length).map (fun k => bs[k]?.getD false) = bs := by apply List.ext_getElem (by simp) intro j _ hj; simp [List.getElem?_eq_getElem hj] private theorem tag_chunk (x y : Nat) (b : Bool) : (phasePair b).map (token x y) = pair x y b := by cases b <;> rfl theorem tokens {h w k : Nat} (size : 1 pair (owner i) (mate i) ((tag i)[j]?.getD false)) (tagPhase (w*h) tag) (by intro j _; exact part (mutableCell (fun u => (tag u)[j]?.getD false)) (List.mem_range.mpr ix)) have proj : (tag i).flatMap (pair (owner i) (mate i)) = (List.range k).flatMap (fun j => pair (owner i) (mate i) ((tag i)[j]?.getD false)) := by conv => lhs; arg 2; rw [← enumerate (tag i)] rw [List.flatMap_map,length i ix] rw [← proj] at fromTags have col := part P455PaddedPorts.roles ((columns_cells h w i).mpr ix) have mid := (ports size ix 5).append (fromTags.append col) have shape : P455CellClassFrames.phase (owner i) (mate i) (tag i) = (List.replicate 5 (P455PaddedPorts.roles i ++ P455PaddedPorts.roles i)).flatten ++ ((tag i).flatMap (pair (owner i) (mate i)) ++ P455PaddedPorts.roles i) := by unfold P455CellClassFrames.phase fixedPhases simp only [List.map_append,List.map_flatMap, tag_chunk,List.append_assoc] rfl rw [shape] simpa only [middle,suffix,List.append_assoc] using mid private theorem role_small {i t a : Nat} (ix : i simpa [mutableCell,b,or_comm] using m simp only [middle,suffix,tail,portChunks,tagPhase,List.mem_append,List.mem_flatMap] at mem rcases mem with (⟨d,_,p⟩|(⟨_,_,j,inR,m⟩|⟨j,jc,m⟩))|⟨j,jr,m⟩ · obtain ⟨j,mj,ma⟩ := List.mem_flatMap.mp p obtain ⟨block,inB,hj⟩ := List.mem_flatMap.mp mj have cell : j∈P455PaddedPorts.cells block := by simpa using hj exact roleMem j ((matching_cells size d j).mp (List.mem_flatMap.mpr ⟨block,inB,cell⟩)) ma · exact mutMem _ j (List.mem_range.mp inR) m · exact roleMem j ((columns_cells h w j).mp jc) m · exact mutMem _ j (List.mem_range.mp jr) m def phases {h w k : Nat} {allow : Tag → Prop} (size : 1 by rw [length i hi] allowed := allowed tokens := fun _ hi => tokens size tag length hi finalPair := fun i hi => (P455CellClass.canonical_final (w*h) i hi) ▸ List.filter_sublist capped := P455PaddedWord.capped size tag _ end P455CellClassPadded end /- Begin Problem455PrefixMatching (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455Quotient P455FirstRewrite P455Witness P455Structural Problem455.Slots open P455DefectProjection (select_cap select_sub) open Problem455Swap (Link) def Changed (u v : Word) (a b : Nat) := select [a,b] u ≠ select [a,b] v theorem changed_symm {u v a b} : Changed u v a b ↔ Changed u v b a := by unfold Changed; rw [select_swap a b u,select_swap a b v] theorem subpair (keep w : Word) {a b : Nat} (ha : a ∈ keep) (hb : b ∈ keep) : select [a,b] (select keep w) = select [a,b] w := select_sub _ _ _ (by simpa using And.intro ha hb) theorem selected_change (keep : Word) {u v a b} (ha : a ∈ keep) (hb : b ∈ keep) : Changed (select keep u) (select keep v) a b ↔ Changed u v a b := by simp only [Changed,subpair keep _ ha hb] theorem selected_edge (keep : Word) {r allow w a b} (ab : a ≠ b) (ha : a ∈ keep) (hb : b ∈ keep) : Edge (select keep w) r allow a b ↔ Edge w r allow a b := by rw [edge_iff ab,edge_iff ab,subpair keep _ ha hb] private theorem overlapping_projection {r allow ts u v a b c} (hr : 0 < r) (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (keep : Word) (small : keep.length ≤ 4) (ha : a∈keep) (hb : b∈keep) (hc : c∈keep) (ab : a ≠ b) (ac : a ≠ c) (bc : b ≠ c) (edit : Changed u v a b) (ec : Edge u r allow a c) : ∃ i j, Link r (select keep u) i j := by classical have eb := (changed_edges cap valid ab edit).1 have overlap : Structural (select keep u) r allow := .inl ⟨⟨keep,small, fun _ m => by simpa only [decide_eq_true_eq] using (List.mem_filter.mp m).2⟩, a,b,c,ab,ac,bc,(selected_edge keep ab ha hb).mpr eb,(selected_edge keep ac ha hc).mpr ec⟩ apply Classical.byContradiction; intro empty have cmp : P455SourceFamilies.Compressed r (select keep u) := fun i j l => empty ⟨i,j,l⟩ have eq := P455StructuralReflection.literal_projection hr cap valid keep small overlap cmp have diff := (selected_change keep ha hb).mpr edit exact diff (congrArg (select [a,b]) eq) private theorem link_names {r w i j} (hr : 0 < r) (cap : Cap r w) (l : Link r w i j) : i∈w ∧ j∈w := by obtain ⟨x,y⟩ := link_counts cap l exact ⟨List.count_pos_iff.mp (x ▸ hr),List.count_pos_iff.mp (y ▸ hr)⟩ theorem neighbors_link {r allow ts u v a b c} (hr : 0 < r) (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (ab : a≠b) (ac : a≠c) (bc : b≠c) (edit : Changed u v a b) (ec : Edge u r allow a c) : Link r (select [a,b,c] u) b c ∨ Link r (select [a,b,c] u) c b := by let k := [a,b,c] have cp := select_cap k cap obtain ⟨i,j,l⟩ := overlapping_projection hr cap valid k (by simp [k]) (by simp [k]) (by simp [k]) (by simp [k]) ab ac bc edit ec have m := link_names hr cp l have hi : i ∈ k := by simpa only [decide_eq_true_eq] using (List.mem_filter.mp m.1).2 have hj : j ∈ k := by simpa only [decide_eq_true_eq] using (List.mem_filter.mp m.2).2 have p := edge_no_links cp ab ((selected_edge k ab (by simp [k]) (by simp [k])).mpr (changed_edges cap valid ab edit).1) have q := edge_no_links cp ac ((selected_edge k ac (by simp [k]) (by simp [k])).mpr ec) simp only [k,List.mem_cons,List.not_mem_nil,or_false] at hi hj rcases hi with hi|hi|hi <;> rcases hj with hj|hj|hj <;> subst i <;> subst j <;> first | exact (not_self hr cp l).elim | exact (p.1 l).elim | exact (p.2 l).elim | exact (q.1 l).elim | exact (q.2 l).elim | exact .inl l | exact .inr l private theorem split_four {r u a b c} (cap : Cap r u) (cmp : P455SourceFamilies.Compressed r u) (l : Link r (select [a,b,c] u) b c) : ∃ z, z ∉ [a,b,c] ∧ ¬ Link r (select [a,b,c,z] u) b c := by classical have count : u.count b = r := by have x := (link_counts (select_cap _ cap) l).1 rwa [P455DefectProjection.select_count _ _ _ (by simp)] at x have miss : ∃ z, ¬ Link r (select [a,b,c,z] u) b c := by apply Classical.byContradiction; intro none apply cmp b c (link_of_triples cap count ?_) intro z have four : Link r (select [a,b,c,z] u) b c := Classical.byContradiction (fun f => none ⟨z,f⟩) have tri := link_project (select_cap _ cap) four [b,c,z] (by simp) (by simp) rwa [select_sub _ _ _ (by simp)] at tri obtain ⟨z,f⟩ := miss refine ⟨z,?_,f⟩ intro old have eq : select [a,b,c,z] u = select [a,b,c] u := by unfold select; apply List.filter_congr; intro t _ by_cases e : t=z · subst t; simp at old; simp [old] · simp [e] exact f (eq ▸ l) private theorem drop_four {a b c z} (fresh : z ∉ [a,b,c]) (w : Word) : dropName z (select [a,b,c,z] w) = select [a,b,c] w := by simp only [dropName,select,List.filter_filter] apply List.filter_congr; intro t _ by_cases e : t=z · subst t; simp at fresh; simp [fresh] · simp [e] /-- Any two changed neighbors ordered by first occurrence contain another changed neighbor strictly between them. The same actual four-name link is used on both sides via identity_link. -/ theorem intermediate_neighbor {r allow ts u v a b c} (hr : 0 < r) (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (cmp : P455SourceFamilies.Compressed r u) (ab : a≠b) (ac : a≠c) (bc : b≠c) (eb : Changed u v a b) (ec : Changed u v a c) (order : u.idxOf b < u.idxOf c) : ∃ z, a≠z ∧ b≠z ∧ c≠z ∧ Changed u v a z ∧ u.idxOf b < u.idxOf z ∧ u.idxOf z < u.idxOf c := by let k := [a,b,c] have ecR := (changed_edges cap valid ac ec).1 have base : Link r (select k u) b c := by rcases neighbors_link hr cap valid ab ac bc eb ecR with l|l · exact l · have rev := (first_select k u (by simp [k] : c∈k) (by simp [k] : b∈k)).mp (link_first hr (select_cap k cap) l) omega obtain ⟨z,fresh,bad⟩ := split_four cap cmp base let four := [a,b,c,z] let U := select four u let V := select four v have zne : z≠a ∧ z≠b ∧ z≠c := by simpa using fresh have ma : a∈four := by simp [four] have mb : b∈four := by simp [four] have mc : c∈four := by simp [four] have mz : z∈four := by simp [four] have cp : Cap r U := select_cap _ cap have id4 := select_valid _ four valid have vcap : Cap r V := fun t => P455CellClassBinary.exact_counts cp id4 t ▸ cp t have reverse : ¬ Link r U c b := by intro l have to3 := link_project cp l k (by simp [k]) (by simp [k]) have eq : select k U = select k u := select_sub _ _ _ (by simp [k,four]) exact no_opposite hr (select_cap k cap) base (eq ▸ to3) have forb := edge_no_links cp ab ((selected_edge four ab ma mb).mpr (changed_edges cap valid ab eb).1) have forc := edge_no_links cp ac ((selected_edge four ac ma mc).mpr ecR) obtain ⟨i,j,l⟩ := overlapping_projection hr cap valid four (by simp [four]) ma mb mc ab ac bc eb ecR have anchor : ∃ p, Link r U p z ∨ Link r U z p := by obtain ⟨pi,pj⟩ := link_names hr cp l have hi : i∈four := by simpa only [decide_eq_true_eq] using (List.mem_filter.mp pi).2 have hj : j∈four := by simpa only [decide_eq_true_eq] using (List.mem_filter.mp pj).2 simp only [four,List.mem_cons,List.not_mem_nil,or_false] at hi hj rcases hi with hi|hi|hi|hi <;> rcases hj with hj|hj|hj|hj <;> subst i <;> subst j <;> first | exact (not_self hr cp l).elim | exact (forb.1 l).elim | exact (forb.2 l).elim | exact (forc.1 l).elim | exact (forc.2 l).elim | exact (bad l).elim | exact (reverse l).elim | exact ⟨_,.inl l⟩ | exact ⟨_,.inr l⟩ have dropped : dropName z U = select k u := drop_four fresh u obtain ⟨bz,zc⟩ := inserted_between hr cp (dropped ▸ base) bad anchor have bv := (identity_link hr cp id4 b z).mp bz have du := linked_shadow cp bz zne.2.1.symm ab.symm zne.1 have dv := linked_shadow vcap bv zne.2.1.symm ab.symm zne.1 have ch : Changed U V a z := by intro equal have e := congrArg (List.map (exchange b z)) ((select_swap z a U).trans (equal.trans (select_swap a z V))) rw [du,dv] at e exact (selected_change four ma mb).mpr eb ((select_swap a b U).trans (e.trans (select_swap b a V))) exact ⟨z,zne.1.symm,zne.2.1.symm,zne.2.2.symm,(selected_change four ma mz).mp ch, (first_select four u mb mz).mp (link_first hr cp bz),(first_select four u mz mc).mp (link_first hr cp zc)⟩ theorem disjoint_changes {r allow ts u v a b c} (hr : 0 < r) (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (cmp : P455SourceFamilies.Compressed r u) (ab : a≠b) (ac : a≠c) (eb : Changed u v a b) (ec : Changed u v a c) : b=c := by classical by_cases bc : b=c · exact bc have no (d : Nat) : ∀ i j, u.idxOf j-u.idxOf i=d → a≠i → a≠j → i≠j → Changed u v a i → Changed u v a j → u.idxOf i < u.idxOf j → False := by induction d using Nat.strongRecOn with | ind d ih => intro i j length ai aj ij ei ej order obtain ⟨z,az,iz,_,ez,lower,upper⟩ := intermediate_neighbor hr cap valid cmp ai aj ij ei ej order exact ih (u.idxOf z-u.idxOf i) (by omega) i z rfl ai az iz ei ez lower rcases neighbors_link hr cap valid ab ac bc eb (changed_edges cap valid ac ec).1 with l|l · have lt := (first_select [a,b,c] u (by simp : b∈[a,b,c]) (by simp : c∈[a,b,c])).mp (link_first hr (select_cap _ cap) l) exact (no _ b c rfl ab ac bc eb ec lt).elim · have lt := (first_select [a,b,c] u (by simp : c∈[a,b,c]) (by simp : b∈[a,b,c])).mp (link_first hr (select_cap _ cap) l) exact (no _ c b rfl ac ab (Ne.symm bc) ec eb lt).elim end P455Prefix end /- Begin Problem455FlipFromWord (from finite-semigroup-identity-bases). -/ section namespace P455FlipFromWord open P455Witness P455Closure P455ChartSchedule P455Structural P455CellClassFrames Problem455.Slots abbrev W := List Nat private theorem profile_head (x y : Nat) (tag : Tag) : profilePrefix x y tag = early x y ++ phase x y tag := by have tags : (tag.flatMap phasePair).map (token x y)=tag.flatMap (Problem455.Slots.pair x y) := by induction tag with | nil => rfl | cons c cs ih => cases c <;> simp [List.flatMap_cons,ih,phasePair,token,Problem455.Slots.pair] simp [profilePrefix,early,phase,fixedPhases,List.replicate_succ,tags,phasePair,token] theorem literal {r allow} (n : Node) (pre post : W) (b : Bool) (cap : P455Closure.Cap r (pre++Problem455.Slots.pair n.owner n.mate b++post)) (recProof : Holds r allow (fun _ _ => False) (pre++Problem455.Slots.pair n.owner n.mate b++post) (typedNode n)) (clean : Closed (pre++Problem455.Slots.pair n.owner n.mate b++post) n.owner n.mate) (cx : pre.count n.owner=r-2) (cy : pre.count n.mate=r-2) : Nonempty (Literal r allow (pre++Problem455.Slots.pair n.owner n.mate b++post) (pre++Problem455.Slots.pair n.owner n.mate (!b)++post) n) := by let x := n.owner let y := n.mate let k := [x,y] obtain ⟨ne,len,allowed,b',pr⟩ := recProof have neq : x≠y := ne have projPair (c : Bool) : select k (Problem455.Slots.pair x y c)=Problem455.Slots.pair x y c := by cases c <;> simp [select,Problem455.Slots.pair,k] change select k (pre++Problem455.Slots.pair x y b++post)=profile x y n.tag b' at pr rw [select_append, select_append, projPair,profile,List.append_assoc] at pr have length : (select k pre).length=(profilePrefix x y n.tag).length := by rw [length_select_pair _ _ neq,profile_prefix_length] change pre.count n.owner + pre.count n.mate = 2*(14+n.tag.length) omega obtain ⟨headEq,tailEq⟩ := List.append_inj pr length obtain ⟨_,endEq⟩ := List.append_inj tailEq (by cases b <;> cases b' <;> rfl) obtain ⟨_,l,t,cut,lx,ly⟩ := clean have prefix₁ : (l++early x y) <+: (pre++Problem455.Slots.pair x y b++post) := ⟨t,cut.symm⟩ have prefix₂ : pre <+: (pre++Problem455.Slots.pair x y b++post) := ⟨_,(List.append_assoc ..).symm⟩ have before : (l++early x y) <+: pre := by rcases List.prefix_or_prefix_of_prefix prefix₁ prefix₂ with yes|reverse · exact yes · obtain ⟨u,eq⟩ := reverse have h := congrArg (List.count x) eq have nl : l.count x=0 := List.count_eq_zero.mpr lx have small : (early x y).count x=3 := by simp [early,List.count_cons,neq,Ne.symm neq] simp only [List.count_append,nl,small,Nat.zero_add] at h change pre.count x=r-2 at cx; omega obtain ⟨m,meq⟩ := before have erase : select k l=[] := select_nil _ _ (fun z mem h => by rcases (show z=x ∨ z=y by simpa [k] using h) with rfl|rfl · exact lx mem · exact ly mem) have fixedEarly : select k (early x y)=early x y := by simp [select,k,early] rw [← meq,select_append,select_append,erase,fixedEarly,List.nil_append,profile_head] at headEq have mid := List.append_cancel_left headEq have subM : (phase x y n.tag).Sublist m := mid ▸ List.filter_sublist .. have subZ : [x,y].Sublist post := endEq ▸ List.filter_sublist .. have cc : P455Closure.Cap r (displayed l x y m post false) := by intro a have h := cap a have eq (c : Bool) : (Problem455.Slots.pair x y c).count a = (Problem455.Slots.pair x y false).count a := by cases c <;> simp [Problem455.Slots.pair,List.count_cons,Nat.add_comm,Nat.add_left_comm] change (pre++Problem455.Slots.pair x y b++post).count a ≤ r at h simp only [← meq,displayed,List.count_append,eq b] at h ⊢ exact h obtain ⟨f,h,hp,hq,hf,words⟩ := from_phases neq n.tag len allowed l m post subM subZ cc refine ⟨⟨f,b,l,h,hp,hq,hf,?_,?_⟩⟩ <;> simpa only [x,y,displayed,meq] using (words _) end P455FlipFromWord end /- Begin Problem455CellClassGrid (from finite-semigroup-identity-bases). -/ section /- Recover exact directional neighbors in the literal rectangle word. Coordinates and type tags are inferred for arbitrary records. -/ namespace P455CellClassGrid open P455RectangleRank P455PaddedMatchings P455PaddedTiles P455PaddedWord P455Witness open P455CellClassClean P455CellClassFrames P455SlotSaturation P455GridRows Problem455.Slots noncomputable section variable {n w h : Nat} {M : MachineTable n} def labels (R : Rectangle M w h) := tagAt w R.tag theorem label_at (R : Rectangle M w h) {y x : Nat} (_hy : y by obtain ⟨tile,eq,_⟩ := yes i ix; rw [← eq,code_length]) yes theorem cell_typed (R : Rectangle M w h) (size : 1 early_groups size (labels R) (constant false) (allowed M) noMark ne hi hj, fun _ hy _ slope => column_order size (labels R) (constant false) (allowed M) noMark hy slope, fun _ _ lt hj => first_owner size (labels R) (constant false) (allowed M) noMark lt hj⟩ theorem port {R : Rectangle M w h} (size : 1 (iff.mp r).2.2.2,fun yes => iff.mpr ⟨cell_typed R size lt,cell_typed R size jt,ord.early i lt j jt ne,yes⟩⟩ private theorem codeLen (R : Rectangle M w h) {y x : Nat} (hy : y decide⟩ have matchId : matching h w p.val=horizontal h w (odd x) := by cases e : odd x <;> simp [p,matching,e] have edges : H R (orientedPort p.val (cell R y x) (cell R v z)) → i≠j → P455PaddedPorts.Block.pair i j ∈ horizontal h w (odd x) := by intro read ne; rw [← matchId]; exact (port size ord p li lj ne).mp read constructor · rintro ⟨horiz,read,_,_⟩ have ne : i≠j := by intro eq; obtain ⟨rfl,rfl⟩ := id_inj hx hz eq obtain ⟨a,b,pa,pb,good⟩ := horiz have same := code_inj (pa.trans pb.symm) exact good.2.2.2.2.2.1 (congrArg Tile.oddColumn same) rw [col] at read obtain ⟨Y,_,X,Xp,_,e1,e2⟩ := (horizontal_edge ..).mp (edges read ne) obtain ⟨yy,xx⟩ := id_inj hx (show X by obtain ⟨_,err⟩ := id_inj hx hz eq; omega have has : P455PaddedPorts.Block.pair i j ∈ horizontal h w (odd x) := (horizontal_edge ..).mpr ⟨y,hy,x,hz,rfl,rfl,rfl⟩ have read := (port size ord p li lj ne).mpr (matchId ▸ has) refine ⟨?_,?_,?_,True.intro⟩ · change (system n).horizontal _ _; rw [coordinates hy hx,coordinates hy hz]; exact R.right y hy x hz · change H R (orientedPort _ _ _); rw [col]; exact read · rw [codeLen R hy hx]; exact ord.column y hy x hz theorem down_iff (R : Rectangle M w h) (size : 1 decide⟩ have matchId : matching h w p.val=vertical h w (odd y) := by cases e : odd y <;> simp [p,matching,e] constructor · rintro ⟨vert,read⟩ have ne : i≠j := by intro eq; obtain ⟨rfl,rfl⟩ := id_inj hx hz eq obtain ⟨a,b,pa,pb,good⟩ := vert have same := code_inj (pa.trans pb.symm) exact good.2.2.2.2.2.1 (congrArg Tile.oddRow same) rw [row] at read have has := (port size ord p li lj ne).mp read rw [matchId] at has obtain ⟨X,_,Y,Yp,_,e1,e2⟩ := (vertical_edge ..).mp has obtain ⟨yy,xx⟩ := id_inj hx (by assumption) e1 obtain ⟨vv,zz⟩ := id_inj hz (by assumption) e2 omega · rintro ⟨rfl,rfl⟩ have ne : i≠j := fun eq => by obtain ⟨err,_⟩ := id_inj hx hz eq; omega have has : P455PaddedPorts.Block.pair i j ∈ vertical h w (odd y) := (vertical_edge ..).mpr ⟨x,hx,y,hv,rfl,rfl,rfl⟩ refine ⟨?_,?_⟩ · change (system n).vertical _ _; rw [coordinates hy hx,coordinates hv hx]; exact R.down y hv x hx · change H R (orientedPort _ _ _); rw [row]; exact (port size ord p li lj ne).mpr (matchId ▸ has) theorem functional {R : Rectangle M w h} (size : 1 have := (right_iff R size ord hy hx hv hz).mp nb have := (right_iff R size ord hy hx hs hq).mp nc omega | left => have := (right_iff R size ord hv hz hy hx).mp nb have := (right_iff R size ord hs hq hy hx).mp nc omega | down => have := (down_iff R size ord hy hx hv hz).mp nb have := (down_iff R size ord hy hx hs hq).mp nc omega | up => have := (down_iff R size ord hv hz hy hx).mp nb have := (down_iff R size ord hs hq hy hx).mp nc omega rw [positions.1,positions.2] end end P455CellClassGrid end /- Begin Problem455PrefixIsolation (from finite-semigroup-identity-bases). -/ section namespace P455Prefix open P455Quotient P455FirstRewrite P455Witness P455Structural Problem455.Slots open Problem455Swap (Link) open P455DefectProjection (select_cap) private theorem linked_changes {r b c a} {u v : Word} (cu : Cap r u) (cv : Cap r v) (ul : Link r u b c) (vl : Link r v b c) (bc : b≠c) (ba : b≠a) (ca : c≠a) : Changed u v b a ↔ Changed u v c a := by have hu := linked_shadow cu ul bc ba ca have hv := linked_shadow cv vl bc ba ca let d := exchange b c have dd : d ∘ d = id := by funext y; by_cases x : y=b <;> by_cases z : y=c <;> simp_all [d,exchange,Function.comp_def,Ne.symm] have inj (t s : Word) (h : t.map d = s.map d) : t=s := by have both := congrArg (List.map d) h simpa only [List.map_map,dd,List.map_id_fun,id_eq] using both constructor · intro changed equal exact changed (hu.symm.trans ((congrArg (List.map d) equal).trans hv)) · intro changed equal apply changed; apply inj; rw [show (select [c,a] u).map d=select [b,a] u from hu, show (select [c,a] v).map d=select [b,a] v from hv,equal] private theorem edge_ne {r allow u a c} (e : Edge u r allow a c) : a≠c := by rcases e with ⟨_,h,_,_,_⟩|⟨_,h,_,_,_⟩ · exact h · exact Ne.symm h theorem incident_record {r allow ts u v a b c} (hr : 0 < r) (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (cmp : P455SourceFamilies.Compressed r u) (ab : a≠b) (eb : Changed u v a b) (ec : Edge u r allow a c) : b=c := by by_cases bc : b=c · exact bc have ac := edge_ne ec let k := [a,b,c] have ma : a∈k := by simp [k] have mb : b∈k := by simp [k] have mc : c∈k := by simp [k] have id3 := select_valid _ k valid have cu := select_cap k cap have cv : Cap r (select k v) := fun t => P455CellClassBinary.exact_counts cu id3 t ▸ cu t have left := changed_symm.mp ((selected_change k ma mb).mpr eb) have right : Changed (select k u) (select k v) c a := by rcases neighbors_link hr cap valid ab ac bc eb ec with l|l · exact (linked_changes cu cv l ((identity_link hr cu id3 b c).mp l) bc ab.symm ac.symm).mp left · exact (linked_changes cu cv l ((identity_link hr cu id3 c b).mp l) (Ne.symm bc) ac.symm ab.symm).mpr left exact disjoint_changes hr cap valid cmp ab ac eb ((selected_change k ma mc).mp (changed_symm.mpr right)) theorem isolated_pair {r allow ts u v a b} (hr : 0 < r) (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (cmp : P455SourceFamilies.Compressed r u) (ab : a≠b) (edit : Changed u v a b) : (∀ c, Edge u r allow a c → b=c) ∧ (∀ c, Edge u r allow b c → a=c) := ⟨fun _ recProof => incident_record hr cap valid cmp ab edit recProof, fun _ recProof => incident_record hr cap valid cmp ab.symm (changed_symm.mp edit) recProof⟩ end P455Prefix end /- Begin Problem455ImmutablePrivate (from finite-semigroup-identity-bases). -/ section /- Protected literal factors pass to a mixed evaluation of the indexed adjacent-swap layout. The target is an arbitrary actual word. -/ namespace P455ImmutablePrivate open P455Structural Problem455.Slots abbrev W := List Nat private def initial (a b : Nat) : List Event := [(a,0),(a,1),(b,0),(a,2),(b,1),(b,2)] theorem stamp_length (n : Nat → Nat) (w : W) : (stamp n w).length=w.length := by induction w generalizing n with | nil => rfl | cons a w ih => simp [stamp,ih] theorem read_names (n : Nat → Nat) (w : W) : (stamp n w).map Prod.fst=w := by induction w generalizing n with | nil => rfl | cons a w ih => simp [stamp,ih] private theorem stamp_low {n : Nat → Nat} {w : W} {a i : Nat} (m : (a,i)∈stamp n w) : n a≤i := by induction w generalizing n with | nil => contradiction | cons b w ih => rcases List.mem_cons.mp m with h|h · cases h; exact Nat.le_refl _ · have lower := ih h simp only [advance] at lower; omega private theorem whole_core {a b : Nat} (ne : a≠b) (l : W) (ax : a∉l) (bx : b∉l) (q : W) : events (l++early a b++q) = events l ++ (initial a b ++ stamp (advance (fun _ => 0) (l++early a b)) q) := by have la := List.count_eq_zero.mpr ax have lb := List.count_eq_zero.mpr bx simp [events,stamp_append,initial,early,stamp,advance,List.count_cons,ne,Ne.symm ne,la,lb] simp only [advance_append,List.append_assoc,List.singleton_append,List.nil_append] rfl private theorem prefix_of_reads {α : Type} (xs ys : List α) (same : ∀ (i : Nat) (e : α), xs[i]?=some e → ys[i]?=some e) : xs <+: ys := by induction xs generalizing ys with | nil => simp | cons a xs ih => have first := same 0 a rfl cases ys with | nil => contradiction | cons b ys => have ab : b=a := Option.some.inj first subst b obtain ⟨q,eq⟩ := ih ys (fun i e h => same (i+1) e h) exact ⟨q,congrArg (List.cons a) eq⟩ /-- Agreement only at the original *immutable* events suffices. This covers partially flipped layouts and avoids assuming the target remains closed or even capped. -/ theorem closed_transport {r : Nat} {u v : W} {a b : Nat} (hr : 5≤r) (closed : Closed u a b) (agree : ∀ (i : Nat) (e : Event), (events u)[i]?=some e → e.2≠r-2 → (events v)[i]?=some e) : Closed v a b := by obtain ⟨ne,l,q,eu,ax,bx⟩ := closed let old := initial a b have core := whole_core ne l ax bx q have atNew (j : Nat) (e : Event) (someE : old[j]?=some e) : (events v)[l.length+j]?=some e := by obtain ⟨bound,fnd⟩ := List.getElem?_eq_some_iff.mp someE have mem : e ∈ old := fnd ▸ List.getElem_mem bound have small : e.2≤2 := by simp only [old,initial,List.mem_cons,List.not_mem_nil,or_false] at mem rcases mem with h|h|h|h|h|h <;> rw [h] <;> simp apply agree _ _ _ (by omega) rw [eu,core,List.getElem?_append_right (by change (stamp (fun _ => 0) l).length ≤ l.length+j rw [stamp_length]; omega)] simp only [events,stamp_length,Nat.add_sub_cancel_left] exact (List.getElem?_append_left bound).trans someE have vlen : l.length 0) low).length=l.length := by simp [stamp_length,low,Nat.min_eq_left (Nat.le_of_lt vlen)] have tail : old <+: stamp (advance (fun _ => 0) low) hi := by apply prefix_of_reads intro i e got have m := atNew i e got change (stamp (fun _ => 0) v)[l.length+i]?=some e at m rw [←split,stamp_append,List.getElem?_append_right (by omega),ll] at m simpa only [show l.length+i-l.length=i by omega] using m obtain ⟨z,ez⟩ := tail have lowFirst (c : Nat) (h : (c,0) ∈ old) : c∉low := by have m : (c,0)∈stamp (advance (fun _ => 0) low) hi := ez ▸ List.mem_append_left z h have le := stamp_low m change 0+low.count c≤0 at le exact List.count_eq_zero.mp (by omega) have fst := congrArg (List.map Prod.fst) ez simp only [List.map_append,read_names] at fst change early a b ++ List.map Prod.fst z = hi at fst exact ⟨ne,low,z.map Prod.fst,by rw [←split,←fst]; simp [List.append_assoc], lowFirst a (by simp [old,initial]),lowFirst b (by simp [old,initial])⟩ end P455ImmutablePrivate end /- Begin Problem455CellClassHalting (from finite-semigroup-identity-bases). -/ section namespace P455CellClassHalting open P455RectangleRank P455PaddedMatchings P455PaddedTiles P455PaddedWord P455Witness open P455CellClassGrid P455CellClassClean P455CellClassSnake P455SlotSaturation P455GridRows variable {n w h : Nat} {M : MachineTable n} private def cert (R : Rectangle M w h) (y x v z : Nat) : EdgeCertificate := ⟨cell R y x,cell R v z,cell R y (x+1),cell R y (x-1),cell R (y+1) x,cell R (y-1) x,cell R (y+1) (x+1)⟩ private theorem guard {R : Rectangle M w h} {b : Bool} {q : Query} (met : b=true → H R q) : H R (flagQ b q) := by cases b <;> first | exact True.intro | exact met rfl theorem local_grid (R : Rectangle M w h) (size : 1 (right_iff R size ord hy hx hy (right on)).mpr ⟨rfl,rfl⟩), guard (fun on => (right_iff R size ord hy (by have := left on; omega) hy hx).mpr ⟨rfl,by have := left on; omega⟩), guard (fun on => (down_iff R size ord hy hx (down on) hx).mpr ⟨rfl,rfl⟩), guard (fun on => (down_iff R size ord (by have := up on; omega) hx hy hx).mpr ⟨by have := up on; omega,rfl⟩),guard ?_,True.intro⟩ intro on; obtain ⟨rr,dd⟩ := Bool.and_eq_true_iff.mp on exact ⟨(down_iff R size ord hy (right rr) (down dd) (right rr)).mpr ⟨rfl,rfl⟩, (right_iff R size ord (down dd) hx (down dd) (right rr)).mpr ⟨rfl,rfl⟩⟩ private theorem end_flag (R : Rectangle M w h) {y x} (hy : y simp [rowEnd,par] at endRow <;> rw [finish] <;> simp [par,endRow] have nb : (system n).bottom e.a.tag=false := by rw [bot]; simp [show y+1≠h by omega] simp only [chosenSuccessor,st,nb,Bool.true_and,Bool.false_eq_true,if_false,if_true] exact ⟨rfl,go⟩ theorem wrap_grid (R : Rectangle M w h) (size : 1 simp [rowEnd,par] at endRow <;> simp [par,endRow] have bot : (system n).bottom e.a.tag=true := by change (system n).bottom (cell R y x).tag = true; rw [coordinates hy hx,f.2.2.2.1]; simp [bottom] have boundI := id_bound hy hx have boundJ := id_bound top left have ne : idAt w y x ≠ idAt w 0 0 := by rw [si,first]; omega have active : H R (orientedPort 4 e.a e.b) := by apply (port size (orders R size) (4 : Fin 5) boundI boundJ ne).mpr exact (wrap_edge ..).mpr ⟨si,first⟩ have go : H R (earlier e.b.owner 0 e.a.owner 0) := by apply (orders R size).first _ _ _ boundI rw [first,si]; omega refine ⟨e,congrArg owner si,congrArg mate si,congrArg owner first,congrArg mate first, readA,readB,local_grid R size hy hx 0 0,?_⟩ simp only [chosenSuccessor,st,bot,Bool.true_and,if_true,allQ,Holds] refine ⟨?_,.inl active,go,True.intro⟩ change ((system n).top (cell R 0 0).tag && (system n).left (cell R 0 0).tag && !(system n).oddRow (cell R 0 0).tag && !(system n).oddColumn (cell R 0 0).tag)=true rw [coordinates top left,z.1,z.2.2.1,z.2.2.2.2.1,z.2.2.2.2.2] decide noncomputable def data (R : Rectangle M w h) (size : 1 next_grid R size hi,fun _ => wrap_grid R size⟩ /-- One fixed monoid for every padding. The only input is an accepting finite-table run with the stated stationary last update and proper initial markers. No existential word layout, query or identity is supplied by the caller. -/ theorem no_basis_of_run {s : Nat} (run : Run M w s) (basis : List (List Nat × List Nat)) (sound : ∀ u v, (u,v) ∈ basis → (P455FullSingleton.model (widthCode n+16) (allowed M) (system n)).Valid u v) : ∃ U V, U ≠ [] ∧ V ≠ [] ∧ (P455FullSingleton.model (widthCode n+16) (allowed M) (system n)).Valid U V ∧ ¬ P455FirstRewrite.Derives (fun u v => (u,v) ∈ basis) U V := by apply P455CellClassClean.no_basis (by omega) _ basis sound intro k obtain ⟨height,_,big,⟨R⟩⟩ := unbounded run (k+2) have size : 1 u.flatMap (fun b => (Problem455Finite.wordsUpTo [false,true] r).map (fun t => ⟨a,b,t⟩))) theorem listed {r allow u n} (typed : Holds r allow noMark u (typedNode n)) : n∈book r u := by obtain ⟨_,len,_,bit,eq⟩ := typed have mem (c : Nat) (hc : c∈profile n.owner n.mate n.tag bit) : c∈u := (List.mem_filter.mp (eq ▸ hc : c∈select [n.owner,n.mate] u)).1 obtain ⟨a,b,t⟩ := n refine List.mem_flatMap.mpr ⟨a,mem _ (by simp [profile,profilePrefix]),List.mem_flatMap.mpr ⟨b,mem _ (by simp [profile,profilePrefix]),List.mem_map.mpr ⟨t,?_,rfl⟩⟩⟩ apply Problem455Finite.covered · dsimp at len; omega · intro x _; cases x <;> simp private theorem index_unique {α : Type} [DecidableEq α] (t : List α) {a b : α} (ma : a∈t) (mb : b∈t) (h : t.idxOf a=t.idxOf b) : a=b := by induction t with | nil => contradiction | cons c t ih => by_cases ca : c=a <;> by_cases cb : c=b · exact ca.symm.trans cb · subst c; simp [List.idxOf_cons,cond_eq_if,beq_iff_eq,cb,Ne.symm cb] at h · subst c; simp [List.idxOf_cons,cond_eq_if,beq_iff_eq,ca,Ne.symm ca] at h · exact ih ((List.mem_cons.mp ma).resolve_left (Ne.symm ca)) ((List.mem_cons.mp mb).resolve_left (Ne.symm cb)) (by simpa [List.idxOf_cons,cond_eq_if,beq_iff_eq,ca,cb,Ne.symm] using h) noncomputable def nodes (r : Nat) (u : W) (i : Nat) : Node := by classical exact if h : ∃ n ∈ book r u, (book r u).idxOf n=i then h.choose else ⟨0,0,[]⟩ theorem node_index {r u n} (m : n∈book r u) : nodes r u ((book r u).idxOf n) = n := by classical have h : ∃ y∈book r u, (book r u).idxOf y=(book r u).idxOf n := ⟨n,m,rfl⟩ simp only [nodes,dif_pos h] exact index_unique _ h.choose_spec.1 m h.choose_spec.2 theorem index_node {r allow u v i} (ok : Holds r allow noMark v (typedNode (nodes r u i))) : (book r u).idxOf (nodes r u i)=i := by classical by_cases h : ∃ n∈book r u, (book r u).idxOf n=i · simpa only [nodes,dif_pos h] using h.choose_spec.2 · have bad := ok.1 simp [nodes,h] at bad def readBit (w : W) (n : Node) : Bool := decide (select [n.owner,n.mate] w=profile n.owner n.mate n.tag true) theorem read_actual {w n bit} (ne : n.owner≠n.mate) (h : select [n.owner,n.mate] w = profile n.owner n.mate n.tag bit) : readBit w n=bit := by cases bit <;> simp_all [readBit,profile,pair] theorem actual_read {r allow w n} (typed : Holds r allow noMark w (typedNode n)) : select [n.owner,n.mate] w = profile n.owner n.mate n.tag (readBit w n) := by obtain ⟨b,h⟩ := typed.2.2.2; rw [read_actual typed.1 h,h] structure PairInfo (r : Nat) (allow : Tag → Prop) (u v : W) (i : Nat) (x y : Event) : Prop where roles : (x.1=(nodes r u i).owner ∧ y.1=(nodes r u i).mate) ∨ (y.1=(nodes r u i).owner ∧ x.1=(nodes r u i).mate) typedU : Holds r allow noMark u (typedNode (nodes r u i)) typedV : Holds r allow noMark v (typedNode (nodes r u i)) bits : readBit v (nodes r u i) = !readBit u (nodes r u i) mutable : x.2=r-2 ∧ y.2=r-2 theorem label_pair {r allow ts u v} (cap : Cap r u) (valid : (P455FullSingleton.model r allow ts).Valid u v) (x y : Event) (hx : P455ChangedEvents.Mates u v r x y) : ∃ i, PairInfo r allow u v i x y := by have ne : x.1≠y.1 := by rintro e apply hx.1 have one (a : Nat) (w : W) : select [a,a] w = List.replicate (w.count a) a := by induction w with | nil => rfl | cons b t ih => by_cases f : b=a <;> simp_all [select,List.count_cons,List.replicate_succ,Ne.symm] rw [e,one,one,P455CellClassBinary.exact_counts cap valid] obtain ⟨a,b,tag,bit,ord,len,ok,ua,va⟩ := P455CellClassBinary.changed cap valid ne hx.1 let n : Node := ⟨a,b,tag⟩ have ab : a≠b := by rcases ord with ⟨p,q⟩|⟨p,q⟩ <;> rw [p,q] <;> first | exact ne | exact Ne.symm ne have pairs (w : W) : select [a,b] w = select [x.1,y.1] w := by rcases ord with ⟨p,q⟩|⟨p,q⟩ <;> rw [p,q]; exact select_swap _ _ _ have U := (pairs u).trans ua have V := (pairs v).trans va have tU : Holds r allow noMark u (typedNode n) := ⟨ab,len,ok,bit,U⟩ have tV : Holds r allow noMark v (typedNode n) := ⟨ab,len,ok,!bit,V⟩ let i := (book r u).idxOf n have idx : nodes r u i = n := node_index (listed tU) refine ⟨i,?_⟩ constructor · rw [idx]; exact ord.elim (fun h => .inl ⟨h.1.symm,h.2.symm⟩) (fun h => .inr ⟨h.1.symm,h.2.symm⟩) · rwa [idx] · rwa [idx] · rw [idx,read_actual (n:=n) ab U,read_actual (n:=n) ab V] · exact hx.2 end P455ChartBuild end /- Begin Problem455MachineReduction (from finite-semigroup-identity-bases). -/ section namespace P455MachineReduction open P455MachineCleanup P455MachineTable P455PaddedTiles def model (M : Ordinary g q) := P455FullSingleton.model (widthCode (g*(q+2+1))+16) (allowed (compile (normalized M))) (system (g*(q+2+1))) theorem no_basis_of_halt (M : Ordinary g q) (halt : ∃ t,stopped M t) (basis : List (List Nat × List Nat)) (sound : ∀ u v,(u,v)∈basis → (model M).Valid u v) : ∃ U V,U ≠ [] ∧ V ≠ [] ∧ (model M).Valid U V ∧ ¬ P455FirstRewrite.Derives (fun u v=>(u,v)∈basis) U V := by obtain ⟨w,s,⟨T⟩⟩ := (halts_iff_trace M).mp halt let R : Run (compile (normalized M)) w s := ⟨T.positive,T.rows,T.start,T.marks,T.steps,T.accept,trace_stutters (normalized M) T⟩ exact P455CellClassHalting.no_basis_of_run R basis sound theorem no_assembly_of_nonhalt (M : Ordinary g q) (nonhalt : ¬∃ t,stopped M t) : ¬Nonempty (P455GridAssembly.Rectangle (allowed (compile (normalized M))) (system (g*(q+2+1)))) := by rintro ⟨R⟩ exact nonhalt ((halts_iff_trace M).mpr ⟨R.width+1,R.height,⟨assembly_trace R⟩⟩) end P455MachineReduction end /- Begin Problem455PrefixChunks (from finite-semigroup-identity-bases). -/ section namespace P455ChartBuild open P455Quotient P455Witness P455FirstRewrite P455Prefix P455WordChart P455Uncrossed P455SlotSaturation open P455Alignment P455ChangedEvents Problem455.Slots inductive Chunk where | fixed (x : Event) | turn (i : Nat) (x y : Event) deriving DecidableEq def row (rev : Nat → Bool) : Chunk → List Event | .fixed x => [x] | .turn i x y => if rev i then [y,x] else [x,y] def render (rev : Nat → Bool) (cs : List Chunk) := cs.flatMap (row rev) def labels (rev : Nat → Bool) (cs : List Chunk) := (render rev cs).map Prod.fst def active (cs : List Chunk) : List Nat := cs.flatMap (fun | .turn i _ _ => [i] | .fixed _ => []) abbrev Orig : Nat → Bool := fun _ => false abbrev Last : Nat → Bool := fun _ => true def AllInfo (r : Nat) (allow : Tag → Prop) (u v : W) (cs : List Chunk) := ∀ i x y, Chunk.turn i x y ∈ cs → PairInfo r allow u v i x y theorem indexed_chunks {r allow ts u v} (hr : 0 rfl | cons a w ih => by_cases e : a=z <;> simp_all [select,List.count_cons,List.replicate_succ,Ne.symm] rw [refl,refl,P455CellClassBinary.exact_counts cap valid] have bs := blocks_of_matching cap valid (fun _ _ _ e f => disjoint_changes hr cap valid cmp (non e) (non f) e f) suffices block_info : ∀ {p q}, Blocks (Mates u v r) p q → ∃ cs, AllInfo r allow u v cs ∧ render Orig cs=p ∧ render Last cs=q from block_info bs intro p q h induction h with | nil => exact ⟨[],fun _ _ _ h => False.elim (List.not_mem_nil h),rfl,rfl⟩ | fixed a _ ih => obtain ⟨cs,info,l,k⟩ := ih refine ⟨.fixed a::cs,?_,?_,?_⟩ · intro i x y m; exact info _ _ _ (by simpa using m) · simp [render,row,← l] · simp [render,row,← k] | pair x y mate _ ih => obtain ⟨cs,info,l,k⟩ := ih obtain ⟨i,recProof⟩ := label_pair cap valid x y mate refine ⟨.turn i x y::cs,?_,?_,?_⟩ · intro j a b m rcases List.mem_cons.mp m with eql|tail · cases eql; exact recProof · exact info _ _ _ tail · simp [render,row,Orig,← l] · simp [render,row,Last,← k] theorem mem_active {cs : List Chunk} {i : Nat} : i ∈ active cs ↔ ∃ x y, Chunk.turn i x y∈cs := by constructor · intro m obtain ⟨q,mem,h⟩ := List.mem_flatMap.mp m cases q with | fixed x => exact False.elim (List.not_mem_nil h) | turn j a b => obtain rfl : i=j := List.mem_singleton.mp h; exact ⟨a,b,mem⟩ · rintro ⟨x,y,h⟩; exact List.mem_flatMap.mpr ⟨.turn i x y,h,List.mem_cons_self⟩ theorem renders_equal {s t : Nat → Bool} (cs : List Chunk) (eq : ∀ i∈active cs, s i=t i) : render s cs=render t cs := by unfold render List.flatMap apply congrArg List.flatten apply List.map_congr_left intro q mem; cases q with | fixed => rfl | turn i x y => simp only [row,eq i (mem_active.mpr ⟨x,y,mem⟩)] theorem pos_perm (s t : Nat → Bool) (cs : List Chunk) : (render s cs).Perm (render t cs) := by induction cs with | nil => exact .refl _ | cons q cs ih => apply List.Perm.append _ ih cases q with | fixed => exact .refl _ | turn i x y => cases e : s i <;> cases f : t i <;> simp only [row,e,f,Bool.false_eq_true,if_false,if_true] <;> first | exact .refl _ | exact .swap _ _ _ theorem original_labels {cs u} (orig : render Orig cs=events u) : labels Orig cs=u := by rw [labels,orig,events,labels_of_stamp] theorem final_labels {cs v} (last : render Last cs=events v) : labels Last cs=v := by rw [labels,last,events,labels_of_stamp] private theorem stamp_swap (n : Nat → Nat) (x y : Nat) (ne : x≠y) (t : W) : stamp n (y::x::t) = (y,n y)::(x,n x)::stamp (advance (advance n [x]) [y]) t := by have oa : advance n [y] x = n x := by simp [advance,ne,Ne.symm ne] have tail : advance (advance n [y]) [x]=advance (advance n [x]) [y] := by funext z; simp [advance]; omega simp only [stamp,oa,tail] /-- Choosing arbitrary orientations preserves the occurrence numbers in every rendered event; the result really is the stamp of its underlying word. -/ theorem stamp_render {r allow u v} (cs : List Chunk) (info : AllInfo r allow u v cs) (n : Nat → Nat) (base : stamp n (labels Orig cs)=render Orig cs) (s : Nat → Bool) : stamp n (labels s cs) = render s cs := by induction cs generalizing n with | nil => rfl | cons q cs ih => have tail : AllInfo r allow u v cs := fun i x y m => info _ _ _ (List.mem_cons_of_mem _ m) cases q with | fixed x => change (x.1,n x.1)::stamp (advance n [x.1]) (labels Orig cs)=x::render Orig cs at base exact List.cons.injEq _ _ _ _ |>.mpr ⟨(List.cons.inj base).1,ih tail _ (List.cons.inj base).2⟩ | turn i x y => have recProof := info i x y List.mem_cons_self have ne : x.1≠y.1 := by rcases recProof.roles with ⟨a,b⟩|⟨a,b⟩ · rw [a,b]; exact recProof.typedU.1 · rw [b,a]; exact Ne.symm recProof.typedU.1 have h := base change stamp n (x.1::y.1::labels Orig cs)=x::y::render Orig cs at h have diff : advance n [x.1] y.1=n y.1 := by simp [advance,ne,Ne.symm ne] simp only [stamp,diff,List.cons.injEq] at h have rest := ih tail _ h.2.2 cases f : s i with | false => simpa only [labels,render,List.flatMap_cons,row,f,Bool.false_eq_true,if_false, List.cons_append,List.nil_append,List.map_cons,stamp,diff,h.1,h.2.1,List.cons.injEq,true_and] using rest | true => simp only [labels,render,List.flatMap_cons,row,f,if_true,List.cons_append,List.nil_append,List.map_cons] rw [stamp_swap n _ _ ne] exact List.cons.injEq _ _ _ _ |>.mpr ⟨h.2.1,List.cons.injEq _ _ _ _ |>.mpr ⟨h.1,rest⟩⟩ theorem immutable {r allow u v} (cs : List Chunk) (info : AllInfo r allow u v cs) (s : Nat→Bool) : ∀ (k : Nat) (e : Event), (render Orig cs)[k]? = some e → e.2 ≠ r-2 → (render s cs)[k]? = some e := by induction cs with | nil => simp [render] | cons q cs ih => have tail : AllInfo r allow u v cs := fun i x y m => info _ _ _ (List.mem_cons_of_mem _ m) cases q with | fixed x => intro k e atK low; cases k with | zero => exact atK | succ k => exact ih tail _ _ atK low | turn i x y => intro k e atK low have ranks := (info i x y List.mem_cons_self).mutable cases k with | zero => exact False.elim (low ((Option.some.inj atK) ▸ ranks.1)) | succ k => cases k with | zero => exact False.elim (low ((Option.some.inj atK) ▸ ranks.2)) | succ k => cases f : s i <;> simpa only [render,List.flatMap_cons,row,f,Bool.false_eq_true,if_false,if_true, List.cons_append,List.nil_append,List.getElem?_cons_succ] using ih tail _ _ atK low end P455ChartBuild end /- Begin Problem455PrefixReadout (from finite-semigroup-identity-bases). -/ section namespace P455ChartBuild open P455Quotient P455Witness P455FirstRewrite P455Prefix P455WordChart open P455SingletonEvaluation P455ChartSchedule P455Schedule P455SlotSaturation Problem455.Slots def Touch (x y a b : Nat) := (x=a ∧ y=b) ∨ (y=a ∧ x=b) theorem touch_symm {a b c d} (h : Touch a b c d) : Touch c d a b := h.elim (fun p => .inl ⟨p.1.symm,p.2.symm⟩) (fun p => .inr ⟨p.2.symm,p.1.symm⟩) theorem touch_trans {a b c d e f} (p : Touch a b c d) (q : Touch c d e f) : Touch a b e f := by rcases p with ⟨h,k⟩|⟨h,k⟩ <;> rcases q with ⟨l,m⟩|⟨l,m⟩ <;> simp_all [Touch] private theorem quiet {a b x y : Nat} (no : ¬Touch x y a b) : select [a,b] [x,y] = select [a,b] [y,x] := by by_cases xa : x=a <;> by_cases xb : x=b <;> by_cases ya : y=a <;> by_cases yb : y=b <;> simp_all [Touch,select] theorem read_projection (cs : List Chunk) (s t : Nat → Bool) (a b : Nat) (same : ∀ i x y, Chunk.turn i x y∈cs → Touch x.1 y.1 a b → s i=t i) : select [a,b] (labels s cs)=select [a,b] (labels t cs) := by induction cs with | nil => rfl | cons q cs ih => have rest := ih (fun i x y m => same i x y (List.mem_cons_of_mem _ m)) simp only [labels,render,List.flatMap_cons,List.map_append] change select [a,b] (((row s q).map Prod.fst) ++ labels s cs) = select [a,b] (((row t q).map Prod.fst) ++ labels t cs) rw [select_append,select_append,rest] apply congrArg (fun w : W => w ++ select [a,b] (labels t cs)) cases q with | fixed => rfl | turn i x y => by_cases h : Touch x.1 y.1 a b · simp only [row,same i x y List.mem_cons_self h] · cases g : s i <;> cases f : t i <;> simp only [row,g,f,Bool.false_eq_true,if_false,if_true,List.map_cons,List.map_nil] <;> first | exact quiet h | exact (quiet h).symm theorem match_roles {n m : Node} (p : Touch n.owner n.mate m.owner m.mate) : Matches n m.owner m.mate := p.elim Or.inl (fun h => .inr ⟨h.2,h.1⟩) theorem one_index {r allow u v a b i j x y f g} (p : PairInfo r allow u v i x y) (q : PairInfo r allow u v j f g) (px : Touch x.1 y.1 a b) (qy : Touch f.1 g.1 a b) : i=j := by have hm : Touch (nodes r u i).owner (nodes r u i).mate (nodes r u j).owner (nodes r u j).mate := touch_trans (touch_symm p.roles) (touch_trans px (touch_trans (touch_symm qy) q.roles)) have eq := P455WordChart.match_unique q.typedU p.typedU (match_roles hm) exact (index_node p.typedU).symm.trans ((congrArg (List.idxOf · (book r u)) eq).trans (index_node q.typedU)) noncomputable def initial (r : Nat) (u : W) : Bits := fun i => readBit u (nodes r u i) def flags (A s : Bits) : Nat → Bool := fun i => s i != A i noncomputable def chooseWord (r : Nat) (u : W) (cs : List Chunk) (s : Bits) := labels (flags (initial r u) s) cs theorem initial_word {r u cs} (src : render Orig cs=events u) : chooseWord r u cs (initial r u)=u := by have base : flags (initial r u) (initial r u)=Orig := funext (fun _ => by simp [flags,Orig]) rw [chooseWord,base,original_labels src] def ending (A : Bits) (C : List Nat) : Bits := fun j => if j∈C then !A j else A j theorem final_word {r u v cs} (dst : render Last cs=events v) : chooseWord r u cs (ending (initial r u) (active cs))=v := by have eq := renders_equal (t := Last) cs (s := flags (initial r u) (ending (initial r u) (active cs))) (fun i m => by cases h : initial r u i <;> simp [flags,ending,m,h,Last]) exact (congrArg (List.map Prod.fst) eq).trans (final_labels dst) private theorem transfer_typed {r allow n w t} (equal : select [n.owner,n.mate] w = select [n.owner,n.mate] t) (ok : Holds r allow noMark w (typedNode n)) : Holds r allow noMark t (typedNode n) := by obtain ⟨d,h⟩ := ok.2.2.2; exact ⟨ok.1,ok.2.1,ok.2.2.1,d,equal.symm.trans h⟩ private theorem choice_projection {r allow u v cs i x y} (info : AllInfo r allow u v cs) (src : render Orig cs=events u) (dst : render Last cs=events v) (use : Chunk.turn i x y∈cs) (a b : Nat) (touch : Touch x.1 y.1 a b) (s : Bits) : let w := chooseWord r u cs s if flags (initial r u) s i then select [a,b] w=select [a,b] v else select [a,b] w=select [a,b] u := by let f := flags (initial r u) s have fixed (j x' y') (m : Chunk.turn j x' y'∈cs) (h : Touch x'.1 y'.1 a b) : i=j := one_index (info i x y use) (info j x' y' m) touch h cases bit : flags (initial r u) s i with | false => simp only [Bool.false_eq_true,if_false] exact (read_projection cs f Orig a b (fun j _ _ m h => (fixed j _ _ m h) ▸ bit)).trans (congrArg _ (original_labels src)) | true => simp only [if_true] exact (read_projection cs f Last a b (fun j _ _ m h => (fixed j _ _ m h) ▸ bit)).trans (congrArg _ (final_labels dst)) theorem mixed_typed {r allow u v cs} (info : AllInfo r allow u v cs) (src : render Orig cs=events u) (dst : render Last cs=events v) (s : Bits) (i : Nat) (m : i∈active cs) : Holds r allow noMark (chooseWord r u cs s) (typedNode (nodes r u i)) := by obtain ⟨x,y,part⟩ := mem_active.mp m have h := info i x y part have p := choice_projection info src dst part _ _ h.roles s split at p · exact transfer_typed p.symm h.typedV · exact transfer_typed p.symm h.typedU theorem mixed_read {r allow u v cs} (info : AllInfo r allow u v cs) (src : render Orig cs=events u) (dst : render Last cs=events v) (s : Bits) (off : Off (active cs) (initial r u) s) : Read s (nodes r u) r allow (chooseWord r u cs s) := by classical intro j typed let n := nodes r u j let w := chooseWord r u cs s change select [n.owner,n.mate] w = profile n.owner n.mate n.tag (s j) by_cases existsPart : ∃ i x y, Chunk.turn i x y∈cs ∧ Touch x.1 y.1 n.owner n.mate · obtain ⟨i,x,y,m,t⟩ := existsPart have h := info i x y m have matched : Matches (nodes r u i) n.owner n.mate := match_roles (touch_trans (touch_symm h.roles) t) have eq := choice_projection info src dst m n.owner n.mate t s have index {z : W} (source : Holds r allow noMark z (typedNode (nodes r u i))) (nOK : Holds r allow noMark z (typedNode n)) : i=j := by have identical := P455WordChart.match_unique nOK source matched exact (index_node source).symm.trans ((congrArg (List.idxOf · (book r u)) identical).trans (index_node typed)) cases flag : flags (initial r u) s i with | false => simp only [flag,Bool.false_eq_true,if_false] at eq have nOK := transfer_typed eq typed have ij := index h.typedU nOK subst i have bit : s j=initial r u j := by simpa [flags] using flag exact eq.trans (by rw [bit]; exact actual_read nOK) | true => simp only [flag,if_true] at eq have nOK := transfer_typed eq typed have ij := index h.typedV nOK subst i have bit : s j= !initial r u j := by cases x : s j <;> cases y : initial r u j <;> simp_all [flags] have bitV : readBit v n=s j := h.bits.trans bit.symm exact eq.trans (by rw [← bitV]; exact actual_read nOK) · have no : j∉active cs := by intro jmem; obtain ⟨x,y,m⟩ := mem_active.mp jmem exact existsPart ⟨j,x,y,m,(info j x y m).roles⟩ have eq : select [n.owner,n.mate] w=select [n.owner,n.mate] u := by exact (read_projection cs (flags (initial r u) s) Orig n.owner n.mate (fun i x y m t => (existsPart ⟨i,x,y,m,t⟩).elim)).trans (congrArg _ (original_labels src)) have nOK := transfer_typed eq typed exact eq.trans (by rw [off j no]; exact actual_read nOK) end P455ChartBuild end /- Begin Problem455PrefixPlaces (from finite-semigroup-identity-bases). -/ section namespace P455ChartBuild open P455Quotient P455Witness P455FirstRewrite P455Prefix P455WordChart P455Uncrossed open P455ChartSchedule P455Schedule P455SlotSaturation Problem455.Slots private theorem marker {r allow u v cs i} (info : AllInfo r allow u v cs) (activeI : i∈active cs) : ((nodes r u i).owner,r-2) ∈ render Orig cs := by obtain ⟨x,y,m⟩ := mem_active.mp activeI have p := info _ _ _ m apply List.mem_flatMap.mpr refine ⟨.turn i x y,m,?_⟩ rcases p.roles with ⟨h,_⟩|⟨h,_⟩ · exact List.mem_cons.mpr (.inl (Prod.ext h p.mutable.1).symm) · exact List.mem_cons.mpr (.inr (List.mem_singleton.mpr (Prod.ext h p.mutable.2).symm)) theorem active_distinct {r allow u v} (cs : List Chunk) (info : AllInfo r allow u v cs) (nd : (render Orig cs).Nodup) : (active cs).Nodup := by induction cs with | nil => simp [active] | cons q cs ih => have tail : AllInfo r allow u v cs := fun i x y m => info _ _ _ (List.mem_cons_of_mem _ m) cases q with | fixed => exact ih tail (List.nodup_cons.mp nd).2 | turn i x y => change (x::y::render Orig cs).Nodup at nd have mx := (List.nodup_cons.mp nd).1 obtain ⟨my,nt⟩ := List.nodup_cons.mp (List.nodup_cons.mp nd).2 change (i::active cs).Nodup refine List.nodup_cons.mpr ⟨?_,ih tail nt⟩ intro mem have m := marker tail mem have p := info i x y List.mem_cons_self rcases p.roles with ⟨h,_⟩|⟨h,_⟩ · exact mx (List.mem_cons_of_mem _ ((show x=((nodes r u i).owner,r-2) from Prod.ext h p.mutable.1).symm ▸ m)) · exact my ((show y=((nodes r u i).owner,r-2) from Prod.ext h p.mutable.2).symm ▸ m) private theorem count_before (n : Nat → Nat) (l t : List Event) (x y : Event) (ne : x.1≠y.1) (h : stamp n ((l++x::y::t).map Prod.fst)=l++x::y::t) : n x.1 + (l.map Prod.fst).count x.1 = x.2 ∧ n y.1 + (l.map Prod.fst).count y.1=y.2 := by simp only [List.map_append,List.map_cons,stamp_append] at h have e := List.append_inj_right h (by rw [P455ImmutablePrivate.stamp_length,List.length_map]) obtain ⟨hx,sub⟩ := List.cons.inj e obtain ⟨hy,_⟩ := List.cons.inj sub exact ⟨congrArg Prod.snd hx,by simpa [advance,ne,Ne.symm ne] using congrArg Prod.snd hy⟩ private theorem flags_switch (A s : Bits) (i : Nat) : flags A (switch s i) i = !flags A s i ∧ ∀ j, j≠i → flags A (switch s i) j=flags A s j := by constructor · cases e : s i <;> cases f : A i <;> simp [flags,P455ChartSchedule.switch,e,f] · intro j ne; simp [flags,P455ChartSchedule.switch,ne] theorem mixed_stamp {r allow u v cs} (info : AllInfo r allow u v cs) (src : render Orig cs=events u) (s : Bits) : events (chooseWord r u cs s) = render (flags (initial r u) s) cs := by exact stamp_render cs info _ (by rw [original_labels src,src]; rfl) _ /-- Actual factorization with identical surrounding words before and after a bit switch, at precisely the r-2 numbered copies of its two names. -/ theorem switched_place {r allow u v cs} (info : AllInfo r allow u v cs) (src : render Orig cs=events u) (s : Bits) (i : Nat) (use : i∈active cs) : let n := nodes r u i ∃ pre post : W, ∃ d : Bool, chooseWord r u cs s = pre ++ pair n.owner n.mate d ++ post ∧ chooseWord r u cs (switch s i) = pre ++ pair n.owner n.mate (!d) ++ post ∧ pre.count n.owner = r-2 ∧ pre.count n.mate = r-2 := by obtain ⟨x,y,m⟩ := mem_active.mp use obtain ⟨p,q,e⟩ := List.append_of_mem m subst cs let f := flags (initial r u) s let g := flags (initial r u) (switch s i) have turn := info i x y m have nd := active_distinct _ info (src ▸ P455Paths.stamp_unique _ _) change (active (p++Chunk.turn i x y::q)).Nodup at nd have ins : active (p++Chunk.turn i x y::q)=active p ++ i::active q := by simp [active,List.flatMap_append] rw [ins] at nd obtain ⟨_,nq,dis⟩ := List.pairwise_append.mp nd have ip : i ∉ active p := fun m => dis i m i List.mem_cons_self rfl have iq := (List.nodup_cons.mp nq).1 have relation := flags_switch (initial r u) s i have eq (cs : List Chunk) (absent : i∉active cs) : render g cs=render f cs := renders_equal cs (fun j m => relation.2 j (fun e => absent (e ▸ m))) have first := eq p ip; have last := eq q iq let pre := labels f p let post := labels f q have orig : stamp (fun _ => 0) ((render Orig p++x::y::render Orig q).map Prod.fst) = render Orig p++x::y::render Orig q := by have stamp0 : stamp (fun _ => 0) (labels Orig (p++Chunk.turn i x y::q))=render Orig (p++Chunk.turn i x y::q) := by rw [original_labels src,src]; rfl simpa [labels,render,List.flatMap_append,Orig,row] using stamp0 have ne : x.1≠y.1 := by rcases turn.roles with ⟨a,b⟩|⟨a,b⟩ <;> rw [a,b] <;> first | exact turn.typedU.1 | exact Ne.symm turn.typedU.1 have cnt := count_before _ _ _ x y ne orig have perm : pre.Perm ((render Orig p).map Prod.fst) := (pos_perm f Orig p).map _ have cx : pre.count x.1 = r-2 := (perm.count_eq x.1).trans ((by simpa using cnt.1 : ((render Orig p).map Prod.fst).count x.1 = x.2).trans turn.mutable.1) have cy : pre.count y.1 = r-2 := (perm.count_eq y.1).trans ((by simpa using cnt.2 : ((render Orig p).map Prod.fst).count y.1 = y.2).trans turn.mutable.2) have view (h : Nat → Bool) : labels h (p++Chunk.turn i x y::q)= labels h p ++ (row h (.turn i x y)).map Prod.fst ++ labels h q := by simp [labels,render,List.flatMap_append,List.append_assoc] have L : chooseWord r u (p++Chunk.turn i x y::q) s = pre ++ (row f (.turn i x y)).map Prod.fst ++ post := view f have R : chooseWord r u (p++Chunk.turn i x y::q) (switch s i)= pre ++ (row g (.turn i x y)).map Prod.fst ++ post := by simpa only [chooseWord,labels,first,last,f,g,pre,post] using view g have flip : g i = !f i := relation.1 dsimp only rcases turn.roles with ⟨xo,ym⟩|⟨yo,xm⟩ · refine ⟨pre,post,f i,?_,?_,xo ▸ cx,ym ▸ cy⟩ · cases d : f i <;> simpa only [row,d,pair,Bool.false_eq_true,if_false,if_true,List.map_cons,List.map_nil,xo,ym] using L · cases d : f i <;> simpa only [row,flip,d,pair,Bool.not_true,Bool.not_false,Bool.false_eq_true,if_false,if_true,List.map_cons,List.map_nil,xo,ym] using R · refine ⟨pre,post,!f i,?_,?_,yo ▸ cy,xm ▸ cx⟩ · cases d : f i <;> simpa only [row,d,pair,Bool.not_true,Bool.not_false,Bool.false_eq_true,if_false,if_true,List.map_cons,List.map_nil,yo,xm] using L · cases d : f i <;> simpa only [row,flip,d,pair,Bool.not_true,Bool.not_false,Bool.false_eq_true,if_false,if_true,List.map_cons,List.map_nil,yo,xm] using R end P455ChartBuild end /- Begin Problem455PrefixChart (from finite-semigroup-identity-bases). -/ section namespace P455ChartBuild open P455Quotient P455Witness P455FirstRewrite P455Prefix P455WordChart P455Uncrossed open P455ChartSchedule P455Schedule P455SlotSaturation P455Structural Problem455.Slots theorem geometry_from_chunks {r allow ts u v cs} (hr : 0 decide exact unequal (readBit u n) (bits.trans data.bits) have both := isolated_pair hr cap valid cmp typed.1 edit have only (z : Nat) (za : z≠n.owner) (zb : z≠n.mate) : ¬ Edge u r allow n.owner z ∧ ¬ Edge u r allow n.mate z := ⟨fun e => zb (both.1 z e).symm,fun e => za (both.2 z e).symm⟩ have closed := P455PrivatePhase.closed_changed cap valid (show Rec u r allow n.owner n.mate from ⟨n.tag,typed⟩) edit only have large : 5≤r := by have := typed.2.1; omega have stamped := mixed_stamp info src s have clean : Closed w n.owner n.mate := P455ImmutablePrivate.closed_transport large closed (by intro k e base immutableI rw [show events w=render (flags (initial r u) s) cs from stamped] exact immutable cs info _ k e (src.symm ▸ base) immutableI) have live := mixed_typed info src dst s i m have perm : w.Perm u := (show w.Perm (labels Orig cs) from (pos_perm _ Orig cs).map _).trans ((original_labels src) ▸ List.Perm.refl _) have cp : Cap r w := fun a => Nat.le_trans (Nat.le_of_eq (perm.count_eq a)) (cap a) obtain ⟨pre,post,bit,start,endWord,ca,cb⟩ := switched_place info src s i m rw [start,endWord] apply P455FlipFromWord.literal n pre post bit · simpa only [w,start,n,Cap,P455Closure.Cap] using cp · simpa only [start] using live · simpa only [w,start] using clean · exact ca · exact cb theorem capped_schedule_or_rectangle {r allow ts u v} (hr : 0 (P455FullSingleton.model r allow ts).Valid a b ∧ rank a b≤P455MarkedRank.bound r) u v ∨ Nonempty (P455GridAssembly.Rectangle allow ts) := by obtain ⟨cs,info,src,dst⟩ := indexed_chunks hr cap valid cmp have g := geometry_from_chunks hr cap valid cmp info src dst let A := initial r u let C := active cs have off : Off C A (ending A C) := by intro i out; simp [ending,out] have diff (i : Nat) (m : i∈C) : A i≠ending A C i := by cases h : A i <;> simp [ending,m,h] have left := initial_word (r:=r) src have right := final_word (r:=r) dst (u:=u) simpa only [A,C,left,right] using normalize_layout law g off diff (left.symm ▸ cap) (left.symm ▸ cmp) (show (P455FullSingleton.model r allow ts).Valid (chooseWord r u cs A) (chooseWord r u cs (ending A C)) by simpa only [A,C,left,right] using valid) /-- Entire arbitrary-word implication. No chart, changed-pair matching, normalization, graph acyclicity or accepting rectangle is supplied. -/ theorem arbitrary_schedule_or_rectangle {r allow ts u v} (hr : 0 (P455FullSingleton.model r allow ts).Valid a b ∧ rank a b ≤ max (P455MarkedRank.bound r) (2*(r+2)+1)) u v ∨ Nonempty (P455GridAssembly.Rectangle allow ts) := by obtain ⟨A,B,h,_,ca,_,cmp,_,ok,_,_,_,_,lift⟩ := normalized_compressed hr valid exact (capped_schedule_or_rectangle hr law ca ok cmp).imp_left (lift _) end P455ChartBuild end /- Begin Problem455Global (from finite-semigroup-identity-bases). -/ section namespace P455Global open P455PaddedTiles P455FiniteBasis P455FirstRewrite abbrev monoid {n} (M : MachineTable n) := P455FullSingleton.model (widthCode n+16) (allowed M) (system n) def Accepts {n} (M : MachineTable n) := ∃ w s, Nonempty (AcceptingTrace M w s) def HasBasis {S : Type} (M : Model S) := ∃ rules, Basis M rules def Stationary {n} (M : MachineTable n) := ∀ {w s}, (T : AcceptingTrace M w s) → ∀ x, x (ok a b m).2.2) exact fail (complete u v un vn idn) /-- The complete basis equivalence for a finite local transition table. The only machine normal-form property is stuttering of a reachable accepting configuration. The two rank implications are proved above. -/ theorem table_equivalence {n} (M : MachineTable n) (stationary : Stationary M) : HasBasis (monoid M) ↔ ¬Accepts M := ⟨fun base accept => no_basis_of_trace M stationary accept base,finite_of_no_trace M⟩ end P455Global end /- Begin Problem455Decision (from finite-semigroup-identity-bases). -/ section namespace P455Decision open P455MachineCleanup P455MachineTable theorem ordinary_equivalence {g q} (M : Ordinary g q) : P455Global.HasBasis (P455MachineReduction.model M) ↔ ¬ ∃ t, stopped M t := by have table := P455Global.table_equivalence (compile (normalized M)) (fun T => trace_stutters (normalized M) T) exact table.trans (not_congr (halts_iff_trace M).symm) end P455Decision end /- Begin Problem455Table (from finite-semigroup-identity-bases). -/ section namespace P455Table open P455FirstRewrite structure FiniteOps where size : Nat one : Fin size mul : Fin size → Fin size → Fin size structure Presents {A : Type} (X : FiniteOps) (M : Model A) where decode : Fin X.size → A inj : ∀ i j, decode i=decode j → i=j surj : ∀ a, ∃ i, decode i=a one_eq : decode X.one=M.unit mul_eq : ∀ i j, decode (X.mul i j)=M.op (decode i) (decode j) /-- An executable list cover and equality test. Neither is obtained by choice. -/ structure Listing (A : Type) where eq : DecidableEq A items : List A all : ∀ x, x∈items def distinct [DecidableEq A] : List A → List A | [] => [] | x::xs => if x∈xs then distinct xs else x::distinct xs theorem mem_distinct [DecidableEq A] (a : A) (xs : List A) : a∈distinct xs ↔ a∈xs := by induction xs with | nil => simp [distinct] | cons x xs ih => by_cases h : x∈xs · simp only [distinct,if_pos h,ih,List.mem_cons] exact ⟨Or.inr,fun v => v.elim (fun e => e ▸ h) id⟩ · simp [distinct,h,ih] theorem nodup_distinct [DecidableEq A] (xs : List A) : (distinct xs).Nodup := by induction xs with | nil => simp [distinct] | cons x xs ih => by_cases h : x∈xs · simpa [distinct,h] using ih · simpa [distinct,h,List.nodup_cons,mem_distinct] using ih def number [DecidableEq A] (a : A) : (xs : List A) → a∈xs → Fin xs.length | [], h => nomatch h | x::xs, h => if e : a=x then ⟨0,by simp⟩ else (number a xs ((List.mem_cons.mp h).resolve_left e)).succ theorem number_get [DecidableEq A] (a : A) (xs : List A) (h : a∈xs) : xs.get (number a xs h) = a := by induction xs with | nil => cases h | cons x xs ih => by_cases e : a=x · subst a; simp [number] · simp only [number,dif_neg e] exact ih _ def finiteOps {A : Type} (L : Listing A) (M : Model A) : FiniteOps := by letI := L.eq let xs := distinct L.items have all (a : A) : a∈xs := (mem_distinct a L.items).mpr (L.all a) exact ⟨xs.length,number _ xs (all M.unit),fun i j => number _ xs (all (M.op (xs.get i) (xs.get j)))⟩ def presentation {A : Type} (L : Listing A) (M : Model A) : Presents (finiteOps L M) M := by letI := L.eq let xs := distinct L.items have all (a : A) : a∈xs := (mem_distinct a L.items).mpr (L.all a) refine ⟨xs.get,?_,fun a => ⟨number a xs (all a),number_get ..⟩,number_get ..,fun i j => number_get ..⟩ intro i j e apply Fin.ext apply (List.getElem?_inj (l := xs) i.isLt (nodup_distinct _)).mp have left : xs[i.val]?=some (xs.get i) := List.getElem?_eq_getElem (by exact i.isLt) have right : xs[j.val]?=some (xs.get j) := List.getElem?_eq_getElem (by exact j.isLt) exact left.trans ((congrArg some e).trans right.symm) abbrev Matrix := List (List Nat) /-- The output contains only multiplication. Numeric names range from zero to the number of rows minus one. -/ def matrix (X : FiniteOps) : Matrix := (List.finRange X.size).map fun i => (List.finRange X.size).map fun j => (X.mul i j).val def entry (T : Matrix) (i j : Nat) := (T[i]?.getD [])[j]?.getD 0 @[simp] theorem matrix_length (X : FiniteOps) : (matrix X).length=X.size := by simp [matrix] theorem matrix_entry (X : FiniteOps) (i j : Fin X.size) : entry (matrix X) i j=(X.mul i j).val := by simp [entry,matrix,List.getElem?_eq_getElem,i.isLt,j.isLt] theorem square (X : FiniteOps) : ∀ row∈matrix X, row.length=X.size ∧ ∀ a∈row, a exact M.blank_ne | some b => exact A.away b theorem tape_snoc (M : Ordinary g q) (A : Alphabet M) (w : List Bool) (b : Bool) : writeAt (inputTape M A w) (w.length+1) (A.bit b)=inputTape M A (w++[b]) := by funext i cases i with | zero => simp [writeAt,inputTape] | succ j => by_cases lt : j Cmd.putRight (A.bit b))) (dataEnv M A p (p.length+1))= dataEnv M A (p++w) ((p++w).length+1) := by induction w generalizing p with | nil => simp [perform] | cons b ws ih => change perform M.marker (ws.map (fun b => Cmd.putRight (A.bit b))) (effect M.marker (.putRight (A.bit b)) (dataEnv M A p (p.length+1))) = _ rw [push_bit,ih] simp theorem rewind (M : Ordinary g q) (A : Alphabet M) (w : List Bool) (k n : Nat) : perform M.marker (List.replicate n (.left : Cmd g)) (dataEnv M A w (k+n))=dataEnv M A w k := by induction n with | zero => rfl | succ n ih => rw [List.replicate_succ] change perform M.marker (List.replicate n .left) (effect M.marker .left (dataEnv M A w (k+n+1))) = _ have one : effect M.marker .left (dataEnv M A w (k+n+1))=dataEnv M A w (k+n) := by simp [effect,dataEnv,write,motion,dest,input_away,write_same] rw [one,ih] def writer (M : Ordinary g q) (A : Alphabet M) (w : List Bool) : List (Cmd g) := Cmd.right :: ((w.map (fun b => Cmd.putRight (A.bit b))) ++ List.replicate (w.length+1) .left) theorem written (M : Ordinary g q) (A : Alphabet M) (w : List Bool) : perform M.marker (writer M A w) (dataEnv M A [] 0)=dataEnv M A w 0 := by have start : effect M.marker .right (dataEnv M A [] 0)=dataEnv M A [] 1 := by simp [effect,dataEnv,motion,write,dest,write_same] simp only [writer,perform,List.foldl_cons,List.foldl_append,start] change perform M.marker (List.replicate (w.length+1) .left) (perform M.marker (w.map (fun b => Cmd.putRight (A.bit b))) (dataEnv M A [] (([] : List Bool).length+1)))=_ rw [put_many] simp only [List.nil_append] simpa using rewind M A w 0 (w.length+1) def blankize (M : Ordinary g q) (A : Alphabet M) (w : List Bool) := install M (writer M A w) theorem blankize_iff (M : Ordinary g q) (A : Alphabet M) (w : List Bool) : (∃ t, stopped (blankize M A w).2 t) ↔ HALT M (inputConfig M A w) := by let e := dataEnv M A [] 0 let cs := writer M A w let N := (install M cs).2 have initial : config₀ N = e.start N := by have m : N.marker=M.marker := installed_marker M cs have b : N.blank=M.blank := installed_blank M cs have f : (fun j => if j=0 then N.marker else N.blank) = inputTape M A [] := by funext j; cases j <;> simp [inputTape,m,b] simp [config₀,e,Env.start,dataEnv,f] exact (blank_halts N).symm.trans (initial ▸ (install_iff M cs e).trans (by change HALT M ((perform M.marker (writer M A w) (dataEnv M A [] 0)).start M) ↔ _ rw [written]; rfl)) def diagonalInput (P : Ordinary g q) (B : Alphabet P) := blankize P B (selfBits P B) theorem diagonal_input_iff (P : Ordinary g q) (B : Alphabet P) : (∃ t, stopped (diagonalInput P B).2 t) ↔ SelfHalt P B := blankize_iff P B _ theorem diagonal_basis (P : Ordinary g q) (B : Alphabet P) : P455Global.HasBasis (P455MachineReduction.model (diagonalInput P B).2) ↔ ¬SelfHalt P B := (P455Decision.ordinary_equivalence _).trans (not_congr (diagonal_input_iff P B)) end P455EffectiveWriter end /- Begin Problem455TableSemantics (from finite-semigroup-identity-bases). -/ section namespace P455TableSemantics open P455Table P455FirstRewrite def SemigroupTable (T : Matrix) : Prop := 0 f a | a, b::w => entry T (f a) (value T f b w) def wordValue (T : Matrix) (f : Nat → Nat) : List Nat → Nat | [] => 0 | a::w => value T f a w def Valid (T : Matrix) (u v : List Nat) := ∀ f : Nat → Nat, (∀ x, f x (a,b)∈rules) u v def code (X : FiniteOps) (f : Nat → Fin X.size) : Nat → List Nat → Fin X.size | x, [] => f x | x, y::ys => X.mul (f x) (code X f y ys) theorem read_code (X : FiniteOps) (f : Nat → Fin X.size) (x : Nat) (w : List Nat) : value (matrix X) (fun a => (f a).val) x w=(code X f x w).val := by induction w generalizing x with | nil => rfl | cons y ys ih => exact (congrArg (entry _ (f x).val) (ih y)).trans (matrix_entry X _ _) theorem decode_code {X : FiniteOps} {M : Model A} (p : Presents X M) (f : Nat → Fin X.size) (x : Nat) (w : List Nat) : p.decode (code X f x w)=M.eval (fun a => p.decode (f a)) (x::w) := by induction w generalizing x with | nil => simp [code,Model.eval,M.oneR] | cons y ys ih => change p.decode (X.mul _ _)=M.op _ _ rw [p.mul_eq,ih] theorem valid_iff {X : FiniteOps} {M : Model A} (p : Presents X M) (u v : List Nat) (un : u≠[]) (vn : v≠[]) : Valid (matrix X) u v ↔ M.Valid u v := by obtain ⟨a,U,rfl⟩ := List.exists_cons_of_ne_nil un obtain ⟨b,V,rfl⟩ := List.exists_cons_of_ne_nil vn constructor · intro h g let f (i : Nat) := Classical.choose (p.surj (g i)) have counts := h (fun x => (f x).val) (fun i => by simp) change value _ _ _ _=value _ _ _ _ at counts rw [read_code,read_code] at counts have E := congrArg p.decode (Fin.ext counts) rw [decode_code,decode_code] at E have fg : (fun i => p.decode (f i))=g := funext fun i => Classical.choose_spec (p.surj (g i)) simpa only [fg] using E · intro h g bounded let f (i : Nat) : Fin X.size := ⟨g i,by simpa using bounded i⟩ change value _ (fun i => (f i).val) _ _=value _ (fun i => (f i).val) _ _ rw [read_code,read_code] exact congrArg Fin.val (p.inj _ _ ((decode_code p f a U).trans ((h (fun i => p.decode (f i))).trans (decode_code p f b V).symm))) theorem basis_iff {X : FiniteOps} {M : Model A} (p : Presents X M) : HasBasis (matrix X) ↔ P455Global.HasBasis M := by constructor <;> rintro ⟨rules,sound,complete⟩ <;> refine ⟨rules,?_,?_⟩ · intro u v m; obtain ⟨a,b,s⟩ := sound u v m exact ⟨a,b,(valid_iff p u v a b).mp s⟩ · intro u v a b s; exact complete u v a b ((valid_iff p u v a b).mpr s) · intro u v m; obtain ⟨a,b,s⟩ := sound u v m exact ⟨a,b,(valid_iff p u v a b).mpr s⟩ · intro u v a b s; exact complete u v a b ((valid_iff p u v a b).mp s) end P455TableSemantics end /- Begin Problem455TableProduct (from finite-semigroup-identity-bases). -/ section namespace P455TableProduct open P455Table P455FirstRewrite def pair (L : Listing A) (K : Listing B) : Listing (A × B) := by letI := L.eq letI := K.eq exact ⟨inferInstance,L.items.flatMap (fun x => K.items.map (Prod.mk x)), fun (x,y) => List.mem_flatMap.mpr ⟨x,L.all x,List.mem_map.mpr ⟨y,K.all y,rfl⟩⟩⟩ def update {I : Type} [DecidableEq I] {F : I → Type} (f : (i : I) → F i) (i : I) (v : F i) : (j : I) → F j := fun j => if h : i=j then h ▸ v else f j def tuples {I : Type} [DecidableEq I] {F : I → Type} (default : (i : I) → F i) (L : (i : I) → Listing (F i)) : List I → List ((i : I) → F i) | [] => [default] | i::xs => (tuples default L xs).flatMap fun f => (L i).items.map (update f i) theorem tuples_cover {I : Type} [DecidableEq I] {F : I → Type} (default : (i : I) → F i) (L : (i : I) → Listing (F i)) (xs : List I) (f : (i : I) → F i) : ∃ g∈tuples default L xs, ∀ i∈xs, g i=f i := by induction xs with | nil => exact ⟨default,by simp [tuples],by simp⟩ | cons j xs ih => obtain ⟨g,hg,ag⟩ := ih refine ⟨update g j (f j),List.mem_flatMap.mpr ⟨g,hg,List.mem_map_of_mem ((L j).all _)⟩,?_⟩ intro i mem by_cases eq : j=i · subst i; simp [update] · exact (dif_neg eq).trans (ag i ((List.mem_cons.mp mem).resolve_left (Ne.symm eq))) def family {I : Type} {F : I → Type} (indices : Listing I) (L : (i : I) → Listing (F i)) (default : (i : I) → F i) : Listing ((i : I) → F i) := by letI := indices.eq letI (i : I) : DecidableEq (F i) := (L i).eq let eq : DecidableEq ((i : I) → F i) := fun f g => if h : ∀ i∈indices.items, f i=g i then isTrue (funext fun i => h i (indices.all i)) else isFalse (fun e => h fun i _ => congrFun e i) refine ⟨eq,tuples default L indices.items,?_⟩ intro f obtain ⟨g,mem,all⟩ := tuples_cover default L indices.items f exact (funext (fun i => all i (indices.all i))) ▸ mem def quotientModel (R : P455Quotient.Rules Nat) (T : List Nat) (cap : P455Quotient.Cap R.r T) : Model (P455Quotient.Q R T) where op := P455Quotient.mul R cap unit := P455Quotient.ofWord R T [] assoc := P455Quotient.mul_assoc R cap oneL x := (P455Quotient.unit_laws R cap x).1 oneR x := (P455Quotient.unit_laws R cap x).2 def quotientListing (R : P455Quotient.Rules Nat) (T : List Nat) (eq : DecidableEq (P455Quotient.Q R T)) : Listing (P455Quotient.Q R T) := ⟨eq,Problem455Finite.carrier R T,Problem455Finite.carrier_complete R T⟩ end P455TableProduct end /- Begin Problem455PrimitivePrim (from finite-semigroup-identity-bases). -/ section /- The primitive tester coordinates, in the enumeration order of the actual product. The computations below are certified in mathlib's Primrec. -/ namespace P455CataloguePrim variable {A B C : Type} [Primcodable A] [Primcodable B] [Primcodable C] theorem filter' {f : A → List B} {p : A → B → Bool} (hf : Primrec f) (hp : Primrec₂ p) : Primrec (fun x => (f x).filter (p x)) := P455GraphPrim.filter hf hp theorem count' [DecidableEq B] : Primrec₂ (fun (xs : List B) (a : B) => xs.count a) := by have f : Primrec (fun p : List B × B => (p.1.filter (fun a => a == p.2)).length) := Primrec.list_length.comp (filter' Primrec.fst ((Primrec.beq.comp Primrec.snd (Primrec.snd.comp Primrec.fst)).to₂)) exact f.of_eq (fun _ => by simp [List.count,List.countP_eq_length_filter]) theorem all' {f : A→List B} {p : A→B→Bool} (hf : Primrec f) (hp : Primrec₂ p) : Primrec (fun a => (f a).all (p a)) := by have h : Primrec (fun a => (f a).foldr (fun b t => p a b && t) true) := Primrec.list_foldr hf (Primrec.const true) ((Primrec.and.comp (hp.comp Primrec.fst (Primrec.fst.comp Primrec.snd)) (Primrec.snd.comp Primrec.snd)).to₂) apply h.of_eq intro x generalize f x = l induction l with | nil => rfl | cons a l ih => simp [ih] theorem mem' [DecidableEq B] : PrimrecRel (fun (a : B) (xs : List B) => a∈xs) := by have h := Primrec.nat_lt.comp (Primrec.const 0) (count'.comp (Primrec.snd (α:=B) (β:=List B)) Primrec.fst) exact h.of_eq (fun _ => by simp [List.count_pos_iff]) theorem distinct' [DecidableEq B] : Primrec (@P455Table.distinct B _) := by have h : Primrec (fun xs : List B => List.recOn (motive := fun _ => List B) xs ([] : List B) (fun a tail result => if a∈tail then result else a::result)) := Primrec.list_rec Primrec.id (Primrec.const []) ((Primrec.ite (mem'.comp (Primrec.fst.comp Primrec.snd) (Primrec.fst.comp (Primrec.snd.comp Primrec.snd))) (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) (Primrec.list_cons.comp (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)))).to₂) apply h.of_eq intro xs induction xs with | nil => rfl | cons a l ih => exact congrArg (fun acc => if a∈l then acc else a::acc) ih theorem words' : Primrec₂ (@Problem455Finite.wordsUpTo B) := P455GraphPrim.wordsUpTo abbrev W := List Nat abbrev Spec := W × Option (List (Nat×Nat)) def accept (r : Nat) (w : W) : Bool := decide (w=List.replicate r 0) || ((w.all (fun a => decide (a=0 ∨ a=1))) && (w.all (fun a => decide (w.count a≤r))) && decide (0 h a simp [accept,P455FirstTesters.power,P455FirstTesters.Binary,List.all_eq_true,cap,and_assoc] theorem accept' : Primrec₂ accept := by let F := Nat×W have p0 : Primrec (fun z : F => List.replicate z.1 0) := (Primrec.list_map (Primrec.list_range.comp Primrec.fst) (Primrec₂.const (0:Nat))).of_eq (fun z=>by simp [List.map_const']) have names : Primrec (fun z : F => z.2.all (fun a => decide (a=0 ∨ a=1))) := all' Primrec.snd ((PrimrecPred.or (Primrec.eq.comp (Primrec.snd (α:=F) (β:=Nat)) (Primrec.const 0)) (Primrec.eq.comp Primrec.snd (Primrec.const 1))).decide.to₂) have cap : Primrec (fun z : F => z.2.all (fun a => decide (z.2.count a ≤ z.1))) := all' Primrec.snd ((Primrec.nat_le.comp (count'.comp (Primrec.snd.comp Primrec.fst) Primrec.snd) (Primrec.fst.comp Primrec.fst)).decide.to₂) have c0 : Primrec (fun z : F => z.2.count 0) := count'.comp Primrec.snd (Primrec.const 0) have c1 : Primrec (fun z : F => z.2.count 1) := count'.comp Primrec.snd (Primrec.const 1) have lo := Primrec.or.comp (Primrec.nat_lt.comp c0 Primrec.fst).decide (Primrec.nat_lt.comp c1 Primrec.fst).decide exact Primrec.or.comp (Primrec.eq.comp Primrec.snd p0).decide (Primrec.and.comp (Primrec.and.comp (Primrec.and.comp (Primrec.and.comp names cap) (Primrec.nat_lt.comp (Primrec.const 0) c0).decide) (Primrec.nat_lt.comp (Primrec.const 0) c1).decide) (lo.of_eq (fun _=>by simp))) def plain (r : Nat) := (Problem455Finite.wordsUpTo [0,1] (2*r)).filter (accept r) theorem plain' : Primrec plain := filter' (words'.comp (Primrec.const [0,1]) (Primrec.nat_mul.comp (Primrec.const 2) Primrec.id)) accept' theorem actual (r : Nat) : (P455Enum.primitive r).list.map Subtype.val = plain r := by unfold P455Enum.primitive P455Enum.selectSub plain simp only [List.map_map,Function.comp_def,List.attach_map_val,List.attach_map_subtype_val] apply List.filter_congr intro a _ apply Bool.eq_iff_iff.mpr simp [accepted] theorem map_distinct {X Y : Type} [DecidableEq X] [DecidableEq Y] (f : X → Y) (inj : Function.Injective f) (s : List X) : (P455Table.distinct s).map f = P455Table.distinct (s.map f) := by induction s with | nil => rfl | cons x xs ih => have mem : f x∈xs.map f ↔ x∈xs := by simp [inj.eq_iff] by_cases m : x∈xs <;> simp [P455Table.distinct,m,mem,ih] def primitive (r : Nat) : List Spec := (P455Table.distinct (P455Enum.primitive r).list).map (fun i => (i.val,none)) theorem primitive' : Primrec primitive := by have hs : Primrec (fun r => (P455Table.distinct (plain r)).map (fun w => (w,(none : Option (List (Nat×Nat)))))) := Primrec.list_map (distinct'.comp plain') ((Primrec.snd.pair (Primrec.const none)).to₂) apply hs.of_eq intro r rw [←actual,←map_distinct Subtype.val Subtype.val_injective,List.map_map] rfl end P455CataloguePrim end /- Begin Problem455TableBits (from finite-semigroup-identity-bases). -/ section /- A self-delimiting bit encoding for the table problem. The order, followed by the n^2 entries in row-major order, are unary numerals. -/ namespace P455TableBits open P455Table P455TableSemantics def unary (n : Nat) := List.replicate n true ++ [false] def readNat : List Bool → Option (Nat × List Bool) | [] => none | false::xs => some (0,xs) | true::xs => (readNat xs).map fun (n,rest) => (n+1,rest) theorem read_unary (n : Nat) (s : List Bool) : readNat (unary n++s)=some (n,s) := by induction n with | zero => rfl | succ n ih => change (readNat (unary n++s)).map _ = _ rw [ih]; rfl def readMany (read : List Bool → Option (A × List Bool)) : Nat → List Bool → Option (List A × List Bool) | 0, s => some ([],s) | n+1, s => do let (a,rest) ← read s let (tail,last) ← readMany read n rest return (a::tail,last) theorem read_many {read : List Bool → Option (A × List Bool)} (emit : A → List Bool) (xs : List A) (ok : ∀ x∈xs, ∀ s, read (emit x ++ s)=some (x,s)) (rest : List Bool) : readMany read xs.length (xs.flatMap emit ++ rest)=some (xs,rest) := by induction xs with | nil => rfl | cons a xs ih => simp only [List.length_cons,List.flatMap_cons,List.append_assoc,readMany,ok a List.mem_cons_self] simp [ih (fun x m => ok x (List.mem_cons_of_mem a m))] def row (xs : List Nat) := xs.flatMap unary def encode (T : Matrix) := unary T.length ++ T.flatMap row def parse (s : List Bool) : Option Matrix := do let (n,rest) ← readNat s let (rows,last) ← readMany (readMany readNat n) n rest if last.isEmpty then some rows else none theorem roundtrip {T : Matrix} (square : ∀ xs∈T, xs.length=T.length) : parse (encode T)=some T := by have row_ok (xs : List Nat) (mem : xs∈T) (s : List Bool) : readMany readNat T.length (row xs ++ s)=some (xs,s) := by rw [←square xs mem] exact read_many unary xs (fun x _ => read_unary x) s have result := read_many row T row_ok [] simp only [List.append_nil] at result simp [parse,encode,read_unary,result] theorem matrix_roundtrip (X : FiniteOps) : parse (encode (matrix X))=some (matrix X) := roundtrip (fun xs m => (P455Table.square X xs m).1.trans (matrix_length X).symm) def Separates (answer : List Bool → Bool → Prop) := ∀ T : Matrix, SemigroupTable T → ∃ b, answer (encode T) b ∧ (b=true ↔ HasBasis T) end P455TableBits end /- Begin Problem455NumericProduct (from finite-semigroup-identity-bases). -/ section /- A first-order direct-product serializer. Runtime values are solely natural numbers, lists of numbers and matrices. -/ namespace P455NumericProduct open P455Table P455FirstRewrite P455FirstTesters def grid (n : Nat) (f : Nat → Nat → Nat) : Matrix := (List.range n).map fun i => (List.range n).map fun j => f i j def tensor (T U : Matrix) : Matrix := let d := U.length grid (T.length*d) (fun i j => entry U (i%d) (j%d) + entry T (i/d) (j/d)*d) def singleton : Matrix := [[0]] def assemble (factors : List Matrix) : Matrix := factors.foldr tensor singleton def pack (i : Fin n) (j : Fin m) : Fin (n*m) := ⟨j.val+i.val*m,by have h := Nat.mul_le_mul_right m i.isLt rw [Nat.succ_mul] at h have v := j.isLt; omega⟩ def major (hm : 0 pack (X.mul (major (positive Y) i) (major (positive Y) j)) (Y.mul (minor (positive Y) i) (minor (positive Y) j))⟩ def prodPresents {M : Model A} {N : Model B} {X Y} (p : Presents X M) (q : Presents Y N) : Presents (prodOps X Y) (combine M N) where decode k := (p.decode (major (positive Y) k),q.decode (minor (positive Y) k)) inj i j eq := by have u := p.inj _ _ (congrArg Prod.fst eq) have v := q.inj _ _ (congrArg Prod.snd eq) have same : pack (major (positive Y) i) (minor (positive Y) i) = pack (major (positive Y) j) (minor (positive Y) j) := by rw [u,v] exact (pack_parts (positive Y) i).symm.trans (same.trans (pack_parts (positive Y) j)) surj := by rintro ⟨a,b⟩ obtain ⟨i,hi⟩ := p.surj a; obtain ⟨j,hj⟩ := q.surj b exact ⟨pack i j,by simp [major_pack,minor_pack,hi,hj]⟩ one_eq := by simp [prodOps,major_pack,minor_pack,combine,p.one_eq,q.one_eq] mul_eq := by intro i j; simp [prodOps,major_pack,minor_pack,combine,p.mul_eq,q.mul_eq] theorem tensor_matrix (X Y : FiniteOps) : tensor (matrix X) (matrix Y)=matrix (prodOps X Y) := by apply List.ext_getElem (by simp [tensor,grid,prodOps]) intro i hi _ have ib : i 0⟩ def unitModel : Model Unit where op _ _ := () unit := () assoc _ _ _ := rfl oneL _ := rfl oneR _ := rfl def unitPresents : Presents unitOps unitModel where decode _ := () inj i j _ := Fin.ext (by have a := i.isLt; have b := j.isLt; change i.val<1 at a; change j.val<1 at b; omega) surj _ := ⟨⟨0,Nat.zero_lt_one⟩,rfl⟩ one_eq := rfl mul_eq _ _ := rfl /-- This specification is used only in the proof, not in the serializer. -/ def Represents (T : Matrix) (M : Model A) := ∃ X, T=matrix X ∧ Nonempty (Presents X M) theorem represents_tensor {M : Model A} {N : Model B} {T U} (a : Represents T M) (b : Represents U N) : Represents (tensor T U) (combine M N) := by obtain ⟨X,rfl,⟨p⟩⟩ := a; obtain ⟨Y,rfl,⟨q⟩⟩ := b exact ⟨prodOps X Y,tensor_matrix _ _,⟨prodPresents p q⟩⟩ structure Coordinate where carrier : Type model : Model carrier raw : Matrix def carrier : List Coordinate → Type | [] => Unit | c::cs => c.carrier × carrier cs def family : (cs : List Coordinate) → Model (carrier cs) | [] => unitModel | c::cs => combine c.model (family cs) /-- This holds for the full list with multiplicities, including empty and singleton families. The raw fold depends only on the lists of numbers. -/ theorem assemble_represents (cs : List Coordinate) (ok : ∀ c∈cs,Represents c.raw c.model) : Represents (assemble (cs.map Coordinate.raw)) (family cs) := by induction cs with | nil => exact ⟨unitOps,rfl,⟨unitPresents⟩⟩ | cons c cs ih => exact represents_tensor (ok c List.mem_cons_self) (ih (fun z hz => ok z (List.mem_cons_of_mem _ hz))) end P455NumericProduct end /- Begin Problem455BinaryTerms (from finite-semigroup-identity-bases). -/ section /- A free-semigroup word and a binary multiplication term describe the same identity modulo associativity. There is no constant constructor. -/ namespace P455BinaryTerms open P455FirstRewrite P455Table P455TableSemantics inductive Term where | var (i : Nat) | mul (s t : Term) deriving DecidableEq def flat : Term → W | .var i => [i] | .mul s t => flat s ++ flat t theorem nonempty (t : Term) : flat t≠[] := by induction t <;> simp_all [flat] def fromHead (x : Nat) : W → Term | [] => .var x | y::w => .mul (.var x) (fromHead y w) def fromWord : W → Term | [] => .var 0 | x::xs => fromHead x xs @[simp] theorem flat_head (x : Nat) (w : W) : flat (fromHead x w)=x::w := by induction w generalizing x with | nil => rfl | cons y ys ih => simp [fromHead,flat,ih] theorem flat_from {w : W} (ne : w≠[]) : flat (fromWord w)=w := by cases w with | nil => contradiction | cons x xs => exact flat_head _ _ def inst (f : Nat → Term) : Term → Term | .var i => f i | .mul s t => .mul (inst f s) (inst f t) theorem flat_inst (f : Nat → Term) (t : Term) : flat (inst f t)=(flat t).flatMap (fun i => flat (f i)) := by induction t <;> simp_all [inst,flat,List.flatMap_append] /-- Ordinary equational deduction in semigroups. The associativity constructor is the instance of one three-variable binary identity. -/ inductive Proof (G : Term → Term → Prop) : Term → Term → Prop | refl (x) : Proof G x x | symm : Proof G x y → Proof G y x | trans : Proof G x y → Proof G y z → Proof G x z | gen : G x y → Proof G x y | mul : Proof G x y → Proof G z t → Proof G (.mul x z) (.mul y t) | subst (f) : Proof G x y → Proof G (inst f x) (inst f y) | assoc (x y z) : Proof G (.mul (.mul x y) z) (.mul x (.mul y z)) private theorem join (G) (a : Nat) (A : W) (b : Nat) (B : W) : Proof G (.mul (fromHead a A) (fromHead b B)) (fromHead a (A++b::B)) := by induction A generalizing a with | nil => exact .refl _ | cons x xs ih => exact .trans (.assoc _ _ _) (.mul (.refl _) (ih x)) theorem norm (G) (x : Term) : Proof G x (fromWord (flat x)) := by induction x with | var x => exact .refl _ | mul s t hs ht => apply Proof.trans (.mul hs ht) obtain ⟨a,A,ea⟩ := List.exists_cons_of_ne_nil (nonempty s) obtain ⟨b,B,eb⟩ := List.exists_cons_of_ne_nil (nonempty t) simp only [flat,ea,eb,fromWord,List.cons_append] exact join G a A b B theorem assoc_eq (G) {s t : Term} (e : flat s=flat t) : Proof G s t := (norm G s).trans (e.symm ▸ (norm G t).symm) def frame (l r : W) (t : Term) : Term := let left := if l=[] then t else .mul (fromWord l) t if r=[] then left else .mul left (fromWord r) theorem flat_frame (l r : W) (t : Term) : flat (frame l r t)=l++flat t++r := by by_cases a : l=[] <;> by_cases b : r=[] <;> simp [frame,a,b,flat,flat_from] theorem proof_frame {G} (l r : W) {x y} (e : Proof G x y) : Proof G (frame l r x) (frame l r y) := by by_cases a : l=[] <;> by_cases b : r=[] <;> simp [frame,a,b] <;> first | exact e | exact .mul (.refl _) e | exact .mul e (.refl _) | exact .mul (.mul (.refl _) e) (.refl _) theorem step_in_terms {G : W → W → Prop} {H} (rules : ∀ u v, G u v → Proof H (fromWord u) (fromWord v)) {a b : W} (step : Step G a b) : Proof H (fromWord a) (fromWord b) := by obtain ⟨u,v,l,r,h,rule,un,vn,ne,rfl,rfl⟩ := step let f (i : Nat) := fromWord (h i) have fold (w : W) (wn : w≠[]) : flat (frame l r (inst f (fromWord w)))=l++w.flatMap h++r := by have ef : (fun i => flat (f i))=h := funext fun i => flat_from (ne i) rw [flat_frame,flat_inst,flat_from wn,ef] have align (w : W) (wn : w≠[]) : Proof H (fromWord (l++w.flatMap h++r)) (frame l r (inst f (fromWord w))) := by have pos : l++w.flatMap h++r≠[] := by rw [←fold w wn]; exact nonempty _ exact assoc_eq H ((flat_from pos).trans (fold w wn).symm) have middle : Proof H (fromWord u) (fromWord v) := rule.elim (fun m => rules _ _ m) (fun m => (rules _ _ m).symm) exact (align u un).trans ((proof_frame l r (.subst f middle)).trans (align v vn).symm) theorem words_to_terms {G : W → W → Prop} {H} (rules : ∀ u v, G u v → Proof H (fromWord u) (fromWord v)) {a b : W} (path : Derives G a b) : Proof H (fromWord a) (fromWord b) := by induction path with | refl => exact .refl _ | snoc _ e ih => exact ih.trans (step_in_terms rules e) theorem terms_to_words {G : W → W → Prop} {H} (rules : ∀ u v, H u v → Derives G (flat u) (flat v)) {a b} (path : Proof H a b) : Derives G (flat a) (flat b) := by induction path with | refl => exact .refl _ | symm _ ih => exact ih.symm (fun e => P455ReductionBoundary.sym_step e) | trans _ _ ih ik => exact ih.trans ik | gen e => exact rules _ _ e | @mul x y z t _ _ ih ik => exact (by simpa using P455Prefix.context_derives [] (flat z) ih : Derives G (flat x++flat z) (flat y++flat z)).trans (by simpa [flat] using P455Prefix.context_derives (flat y) [] ik) | subst f _ ih => simp only [flat_inst] exact P455Prefix.substitute_deduction _ (fun i => nonempty (f i)) ih | assoc x y z => simp [flat,List.append_assoc,P455Quotient.Walk.refl] end P455BinaryTerms end /- Begin Problem455TableFactors (from finite-semigroup-identity-bases). -/ section /- These finite catalogues and quotient equalities are plugged into the concrete compiler by the output module. Functions here assemble exactly the dependent products used in the rank theorem. -/ namespace P455TableFactors open P455Table P455TableProduct P455FirstRewrite P455Witness P455Paths abbrev Whole (r : Nat) (allow : Tag → Prop) (ts : Tiles) := P455FirstTesters.Carrier r × ((P455GuardProduct.Carrier r allow ts × P455EdgeProduct.Carrier r allow ts) × (P455BinaryProduct.Carrier r allow × P455StructuralProduct.Carrier r allow)) def components {I : Type} (C : Listing I) (rs : I → P455Quotient.Rules Nat) (ts : I → List Nat) (eq : ∀ i, DecidableEq (P455Quotient.Q (rs i) (ts i))) : Listing ((i : I) → P455Quotient.Q (rs i) (ts i)) := family C (fun i => quotientListing _ _ (eq i)) (fun i => P455Quotient.zero (rs i) (ts i)) structure Catalogues (r : Nat) (allow : Tag → Prop) (ts : Tiles) where primitive : Listing (P455FirstTesters.Index r) binary : Listing (P455BinaryProduct.Index r allow) structural : Listing (P455StructuralProduct.Index r allow) guard : Listing (P455GuardProduct.Index r allow ts) edge : Listing (P455EdgeProduct.Index r allow ts) structure EqualityTests (r : Nat) (allow : Tag → Prop) (ts : Tiles) where plain : ∀ T : List Nat, DecidableEq (P455Quotient.Q (P455FirstTesters.plain r) T) binary : ∀ i : P455BinaryProduct.Index r allow, DecidableEq (P455Quotient.Q i.R i.T) guard : ∀ i : P455GuardProduct.Index r allow ts, DecidableEq (P455Quotient.Q i.R i.T) edge : ∀ i : P455EdgeProduct.Index r allow ts, DecidableEq (P455Quotient.Q i.R i.T) def listing {r allow ts} (C : Catalogues r allow ts) (E : EqualityTests r allow ts) : Listing (Whole r allow ts) := pair (components C.primitive (fun _ => P455FirstTesters.plain r) Subtype.val (fun i => E.plain i.val)) (pair (pair (components C.guard _ _ E.guard) (components C.edge _ _ E.edge)) (pair (components C.binary _ _ E.binary) (components C.structural (fun _ => P455FirstTesters.plain r) _ (fun i => E.plain i.T)))) end P455TableFactors end /- Begin Problem455EffectiveQTable (from finite-semigroup-identity-bases). -/ section namespace P455EffectiveQTable open P455Quotient P455Table P455TableProduct abbrev W := List Nat def plainEq (r : Nat) (T : W) : DecidableEq (Q (P455FirstTesters.plain r) T) := P455EffectiveQ.decEq _ (fun _ _ => false) (fun _ _ => by simp [P455FirstTesters.plain]) T def plainListing (r : Nat) (T : W) := quotientListing (P455FirstTesters.plain r) T (plainEq r T) def plainOps (r : Nat) (T : W) (cap : Cap r T) := finiteOps (plainListing r T) (quotientModel _ T cap) def plainPresents (r : Nat) (T : W) (cap : Cap r T) : Presents (plainOps r T cap) (quotientModel (P455FirstTesters.plain r) T cap) := presentation .. section variable {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) def markedListing (r : Nat) (T : W) := quotientListing (Problem455Finite.rules r allow mark) T (P455EffectiveQMove.markedEq tag_ok mark_ok r T) def markedOps (r : Nat) (T : W) (cap : Cap r T) := finiteOps (markedListing tag_ok mark_ok r T) (quotientModel _ T cap) def markedPresents (r : Nat) (T : W) (cap : Cap r T) : Presents (markedOps tag_ok mark_ok r T cap) (quotientModel (Problem455Finite.rules r allow mark) T cap) := presentation .. end end P455EffectiveQTable end /- Begin Problem455MachineParse (from finite-semigroup-identity-bases). -/ section /- Constructive bit-level decoding for the ordinary program and the two input-alphabet names in the diagonal construction. -/ namespace P455MachineParse open P455EffectiveMachine P455MachineLocal P455MachineCleanup open P455TableBits (readNat readMany read_unary read_many) abbrev Bits := List Bool abbrev Parser (α : Type) := Bits → Option (α × Bits) abbrev Programs := (g : Nat) × (q : Nat) × Code g q def asFin (n k : Nat) : Option (Fin n) := if h : k some none | k+1 => do let z ← asFin q ((k/3)/g) let a ← asFin g ((k/3)%g) let d := if k%3=0 then Direction.left else if k%3=1 then Direction.stay else Direction.right return some ⟨z,a,d⟩ theorem entry_roundtrip (x : Option (Ins (Fin g) (Fin q))) : decodeEntry g q (entryCode g x)=some x := by cases x with | none => rfl | some ins => obtain ⟨z,a,d⟩ := ins have gp : 0 decide simp only [decodeEntry,Nat.mul_add_div (by decide : 0<3),Nat.div_eq_of_lt small, Nat.add_zero,Nat.mul_add_mod,Nat.mod_eq_of_lt small,split₁,split₂,asFin_val,Option.bind_some] cases d <;> rfl def fromN (f : Nat → Option α) : Parser α := fun s=>do let (k,tail) ← readNat s let a ← f k return (a,tail) def readVec (n : Nat) (parse : Parser α) : Parser (Vector α n) := fun s=>do let (xs,tail) ← readMany parse n s if h : xs.length=n then return (⟨xs.toArray,by simpa using h⟩,tail) else none theorem vec_read (parse : Parser α) (emit : α → Bits) (ok : ∀ x s,parse (emit x++s)=some (x,s)) (v : Vector α n) (s : Bits) : readVec n parse (v.toList.flatMap emit++s)=some (v,s) := by have h := read_many emit v.toList (fun x _ => ok x) s rw [Vector.length_toList] at h simp [readVec,h,Vector.length_toList] cases v <;> simp [Vector.toList] def rowBits (g : Nat) (v : Vector (Option (Ins (Fin g) (Fin q))) g) := v.toList.flatMap (fun x => unary (entryCode g x)) def parsePayload : Parser Programs := fun s=>do let (g,t) ← readNat s let (q,t) ← readNat t let (mark,t) ← fromN (asFin g) t let (blank,t) ← fromN (asFin g) t let (start,t) ← fromN (asFin q) t let (rows,t) ← readVec q (readVec g (fromN (decodeEntry g q))) t return (⟨g,q,mark,blank,start,rows⟩,t) theorem payload_roundtrip (C : Code g q) (s : Bits) : parsePayload (C.bits++s)=some (⟨g,q,C⟩,s) := by have one (x : Option (Ins (Fin g) (Fin q))) (t : Bits) : fromN (decodeEntry g q) (unary (entryCode g x)++t)=some (x,t) := by simp [fromN,show P455EffectiveMachine.unary=P455TableBits.unary from rfl,read_unary,entry_roundtrip] have row_read (v : Vector (Option (Ins (Fin g) (Fin q))) g) (t : Bits) : readVec g (fromN (decodeEntry g q)) (rowBits g v++t)=some (v,t) := vec_read _ _ one v t have rows := vec_read _ _ row_read C.rows s have eq : C.bits = unary g ++ unary q ++ unary C.marker.val ++ unary C.blank.val ++ unary C.start.val ++ C.rows.toList.flatMap (rowBits g) := by simp only [Code.bits,Code.numerals,List.flatMap_append,List.flatMap_cons,List.flatMap_nil,List.append_nil,List.append_assoc] congr 1 generalize C.rows.toList = xs induction xs with | nil => rfl | cons a xs ih => simp only [List.append_cancel_left_eq] at ih; simp [List.flatMap_append,rowBits,List.flatMap_map,Function.comp_def,ih] have readN (k : Nat) (t : Bits) : readNat (unary k++t)=some (k,t) := read_unary k t have readF {m} (a : Fin m) (t : Bits) : fromN (asFin m) (unary a.val++t)=some (a,t) := by simp [fromN,readN] rw [eq] simp [parsePayload,List.append_assoc,readN,readF,rows] def exactParse (p : Parser α) (s : Bits) : Option α := do let (v,t) ← p s if t.isEmpty then some v else none def parseCode := exactParse parsePayload @[simp] theorem code_roundtrip (C : Code g q) : parseCode C.bits=some ⟨g,q,C⟩ := by have ok := payload_roundtrip C [] simp [parseCode,exactParse,List.append_nil] at ok ⊢ rw [ok]; rfl end P455MachineParse end /- Begin Problem455IndexedProduct (from finite-semigroup-identity-bases). -/ section /- First-order assembly of all raw coordinate tables. The mathematical product retains one coordinate per original index. -/ namespace P455IndexedProduct open P455Table P455NumericProduct P455FirstRewrite P455FirstTesters theorem transport {A B : Type} {M : Model A} {N : Model B} {T : Matrix} (present : Represents T M) (f : A → B) (inj : ∀ x y, f x=f y → x=y) (surj : ∀ y, ∃ x, f x=y) (unit : f M.unit=N.unit) (mul : ∀ x y, f (M.op x y)=N.op (f x) (f y)) : Represents T N := by obtain ⟨X,rfl,⟨p⟩⟩ := present exact ⟨X,rfl,⟨⟨fun i => f (p.decode i),fun i j eq => p.inj i j (inj _ _ eq),by intro y; obtain ⟨x,rfl⟩ := surj y; obtain ⟨i,e⟩ := p.surj x; exact ⟨i,congrArg f e⟩, (congrArg f p.one_eq).trans unit,fun i j => (congrArg f (p.mul_eq i j)).trans (mul _ _)⟩⟩⟩ abbrev Sections {I : Type} (F : I → Type) (s : List I) := (i : I) → i∈s → F i def restricted {I : Type} {F : I → Type} (models : (i:I) → Model (F i)) (s : List I) : Model (Sections F s) where op a b i h := (models i).op (a i h) (b i h) unit i _ := (models i).unit assoc _ _ _ := funext (fun i => funext fun _ => (models i).assoc ..) oneL _ := funext fun i => funext fun _ => (models i).oneL _ oneR _ := funext fun i => funext fun _ => (models i).oneR _ def full {I : Type} {F : I → Type} (models : (i : I) → Model (F i)) : Model ((i : I) → F i) where op f g i := (models i).op (f i) (g i) unit i := (models i).unit assoc _ _ _ := funext fun i => (models i).assoc .. oneL _ := funext fun i => (models i).oneL _ oneR _ := funext fun i => (models i).oneR _ def glue {I : Type} [DecidableEq I] {F : I → Type} (j : I) (s : List I) (v : F j × Sections F s) : Sections F (j::s) := fun i h => if eq : j=i then eq ▸ v.1 else v.2 i ((List.mem_cons.mp h).resolve_left (Ne.symm eq)) private theorem glue_inj {I : Type} [DecidableEq I] {F : I → Type} (j : I) (s : List I) (fresh : j∉s) (u v : F j × Sections F s) (e : glue j s u=glue j s v) : u=v := by apply Prod.ext · simpa [glue] using congrArg (fun f : Sections F (j::s) => f j List.mem_cons_self) e · funext i h have diff : j≠i := fun eq => fresh (eq ▸ h) simpa [glue,diff] using congrArg (fun f : Sections F (j::s) => f i (List.mem_cons_of_mem _ h)) e private theorem glue_surj {I : Type} [DecidableEq I] {F : I → Type} (j : I) (s : List I) (v : Sections F (j::s)) : ∃ u, glue j s u=v := by refine ⟨(v j List.mem_cons_self,fun i h => v i (List.mem_cons_of_mem _ h)),?_⟩ funext i h by_cases eq : j=i · subst i; simp [glue] · simp [glue,eq] theorem partial_product {I : Type} [DecidableEq I] {F : I → Type} (models : (i : I) → Model (F i)) (raw : I → Matrix) (ok : ∀ i, Represents (raw i) (models i)) (s : List I) (nd : s.Nodup) : Represents (assemble (s.map raw)) (restricted models s) := by induction s with | nil => let send (_ : Unit) : Sections F [] := fun _ h => nomatch h apply transport (M:=unitModel) (f:=send) ⟨unitOps,rfl,⟨unitPresents⟩⟩ · intro _ _ _; rfl · intro y; exact ⟨(),funext fun _ => funext fun h => nomatch h⟩ · exact funext fun _ => funext fun h => nomatch h · intro _ _; exact funext fun _ => funext fun h => nomatch h | cons j s ih => have info := List.nodup_cons.mp nd apply transport (represents_tensor (ok j) (ih info.2)) (glue j s) (glue_inj j s info.1) (glue_surj j s) · funext i h by_cases eq : j=i · subst i; simp [glue,combine,restricted] · simp [glue,eq,combine,restricted] · intro u v; funext i h by_cases eq : j=i · subst i; simp [glue,combine,restricted] · simp [glue,eq,combine,restricted] theorem complete_product {I : Type} [DecidableEq I] {F : I → Type} (models : (i : I) → Model (F i)) (raw : I → Matrix) (ok : ∀ i, Represents (raw i) (models i)) (s : List I) (nd : s.Nodup) (all : ∀ i, i∈s) : Represents (assemble (s.map raw)) (full models) := by apply transport (partial_product models raw ok s nd) (fun f i => f i (all i)) · intro f g eq; exact funext fun i => funext fun _ => congrFun eq i · intro g; exact ⟨fun i _ => g i,rfl⟩ · rfl · intro _ _; rfl end P455IndexedProduct end /- Begin Problem455NumericProductPrim (from finite-semigroup-identity-bases). -/ section /- Primitive-recursive numeric product on the standard mathlib encodings of matrices. The theorem refers to the actual first-order core function. -/ namespace P455NumericProductPrim open P455Table P455NumericProduct variable {A : Type} [Primcodable A] theorem entry' {T : A→Matrix} {i j : A→Nat} (t : Primrec T) (a : Primrec i) (b : Primrec j) : Primrec (fun x => entry (T x) (i x) (j x)) := by have row := Primrec.option_getD.comp (Primrec.list_getElem?.comp t a) (Primrec.const []) exact Primrec.option_getD.comp (Primrec.list_getElem?.comp row b) (Primrec.const 0) theorem grid' {n : A→Nat} {f : A→Nat→Nat→Nat} (dim : Primrec n) (elem : Primrec (fun p : (A×Nat)×Nat => f p.1.1 p.1.2 p.2)) : Primrec fun x => grid (n x) (f x) := by exact Primrec.list_map (Primrec.list_range.comp dim) (Primrec₂.mk (Primrec.list_map (Primrec.list_range.comp (dim.comp Primrec.fst)) elem.to₂)) theorem tensor' : Primrec₂ tensor := by apply Primrec₂.mk apply grid' (Primrec.nat_mul.comp (Primrec.list_length.comp Primrec.fst) (Primrec.list_length.comp Primrec.snd)) let Src := ((Matrix×Matrix)×Nat)×Nat have l : Primrec (fun a : Src => a.1.1.1) := Primrec.fst.comp (Primrec.fst.comp Primrec.fst) have r : Primrec (fun a : Src => a.1.1.2) := Primrec.snd.comp (Primrec.fst.comp Primrec.fst) have d := Primrec.list_length.comp r have i : Primrec (fun a : Src => a.1.2) := Primrec.snd.comp Primrec.fst have j : Primrec (fun a : Src => a.2) := Primrec.snd exact Primrec.nat_add.comp (entry' r (Primrec.nat_mod.comp i d) (Primrec.nat_mod.comp j d)) (Primrec.nat_mul.comp (entry' l (Primrec.nat_div.comp i d) (Primrec.nat_div.comp j d)) d) theorem assemble' : Primrec assemble := by exact Primrec.list_foldr (h:=fun (_ : List Matrix) (p : Matrix × Matrix) => tensor p.1 p.2) (Primrec.id (α:=List Matrix)) (Primrec.const P455NumericProduct.singleton) (Primrec₂.mk (tensor'.comp (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp Primrec.snd))) theorem unary : Primrec P455TableBits.unary := by have bits : Primrec (fun n : Nat => (List.range n).map (fun _ => true)) := Primrec.list_map Primrec.list_range (Primrec₂.const true) exact (Primrec.list_append.comp bits (Primrec.const [false])).of_eq (fun _ => by simp [P455TableBits.unary,List.map_const']) theorem row : Primrec P455TableBits.row := Primrec.list_flatMap Primrec.id (unary.comp Primrec.snd).to₂ theorem encode : Primrec P455TableBits.encode := Primrec.list_append.comp (unary.comp Primrec.list_length) (Primrec.list_flatMap Primrec.id (row.comp Primrec.snd).to₂) theorem bits_of_product : Primrec (fun cs => P455TableBits.encode (assemble cs)) := encode.comp assemble' end P455NumericProductPrim end /- Begin Problem455BinaryBasis (from finite-semigroup-identity-bases). -/ section /- Binary multiplication terms on every valid tabulated semigroup. The two definitions of finite basability have equivalent truth values. -/ namespace P455BinaryBasis open P455BinaryTerms P455FirstRewrite P455Table P455TableSemantics def eval (T : Matrix) (f : Nat → Nat) : Term → Nat | .var x => f x | .mul s t => entry T (eval T f s) (eval T f t) def ValidTerm (T : Matrix) (s t : Term) := ∀ f : Nat → Nat, (∀ x, f x (x,y)∈rules) s t theorem entry_lt {T : Matrix} (good : SemigroupTable T) {i j : Nat} (hi : i exact bounded a | cons b xs ih => exact entry_lt good (bounded a) (ih b) theorem concatenate {T : Matrix} (good : SemigroupTable T) {f : Nat → Nat} (bounded : ∀ i, f i rfl | cons x xs ih => simp only [List.cons_append,value,ih] exact (good.2.2 _ _ _ (bounded a) (value_lt good bounded x xs) (value_lt good bounded b B)).symm theorem eval_flat {T : Matrix} (good : SemigroupTable T) {f : Nat → Nat} (bounded : ∀ i, f i rfl | mul s t ih ik => simp only [eval,flat,ih,ik] obtain ⟨a,A,e⟩ := List.exists_cons_of_ne_nil (nonempty s) obtain ⟨b,B,h⟩ := List.exists_cons_of_ne_nil (nonempty t) rw [e,h] exact (concatenate good bounded a A b B).symm theorem valid_flat {T : Matrix} (good : SemigroupTable T) (s t : Term) : ValidTerm T s t ↔ Valid T (flat s) (flat t) := by constructor <;> intro h f bounded · exact (eval_flat good bounded s).symm.trans ((h f bounded).trans (eval_flat good bounded t)) · exact (eval_flat good bounded s).trans ((h f bounded).trans (eval_flat good bounded t).symm) private theorem word_rule {rules : List (W×W)} {u v : W} (m : (u,v)∈rules) (un : u≠[]) (vn : v≠[]) : Derives (fun a b => (a,b)∈rules) u v := .snoc (.refl u) ⟨u,v,[],[],fun i => [i],.inl m,un,vn,by simp,by simp,by simp⟩ theorem basis_iff_words {T : Matrix} (good : SemigroupTable T) : HasTermBasis T ↔ HasBasis T := by constructor · rintro ⟨terms,sound,complete⟩ let words := terms.map (fun p => (flat p.1,flat p.2)) refine ⟨words,?_,?_⟩ · intro u v m obtain ⟨⟨s,t⟩,mem,e⟩ := List.mem_map.mp m cases e exact ⟨nonempty _,nonempty _,(valid_flat good _ _).mp (sound _ _ mem)⟩ · intro u v un vn ok have valid : ValidTerm T (fromWord u) (fromWord v) := (valid_flat good _ _).mpr (by simpa only [flat_from un,flat_from vn] using ok) have derive := terms_to_words (G:=fun x y => (x,y)∈words) (fun s t m => word_rule (List.mem_map_of_mem m) (nonempty s) (nonempty t)) (complete _ _ valid) simpa only [flat_from un,flat_from vn] using derive · rintro ⟨words,sound,complete⟩ let terms := words.map (fun p => (fromWord p.1,fromWord p.2)) refine ⟨terms,?_,?_⟩ · intro s t m obtain ⟨⟨u,v⟩,mem,e⟩ := List.mem_map.mp m cases e obtain ⟨un,vn,ok⟩ := sound _ _ mem apply (valid_flat good _ _).mpr simpa only [flat_from un,flat_from vn] using ok · intro s t ok have derive := complete _ _ (nonempty s) (nonempty t) ((valid_flat good _ _).mp ok) have path := words_to_terms (H:=fun x y => (x,y)∈terms) (fun _ _ m => Proof.gen (List.mem_map_of_mem m)) derive exact (norm _ s).trans (path.trans (norm _ t).symm) end P455BinaryBasis end /- Begin Problem455Encoded (from finite-semigroup-identity-bases). -/ section namespace P455Encoded open P455Table P455TableFactors P455PaddedTiles P455FirstRewrite open P455MachineCleanup P455MachineTable P455EffectiveMachine def useCover {I : Type} [DecidableEq I] (c : P455Enum.Cover I) : Listing I := ⟨inferInstance,c.list,c.mem⟩ def indices {n} (M : MachineTable n) : Catalogues (widthCode n+16) (allowed M) (system n) where primitive := useCover (P455Enum.primitive _) binary := useCover (P455Enum.binary _ M) structural := useCover (P455Enum.structural (by omega) M) guard := useCover (P455Enum.guard (by omega) M) edge := useCover (P455Enum.edge (by omega) M) private def markEq {n} (M : MachineTable n) {mark : Nat → Nat → Prop} (d : DecidableRel mark) (r : Nat) (T : List Nat) : DecidableEq (P455Quotient.Q (Problem455Finite.rules r (allowed M) mark) T) := P455EffectiveQMove.markedEq (fun _ => P455Enum.mem_tags (M := M)) (marks := fun a b => @decide (mark a b) (d a b)) (fun a b => Iff.of_eq (@decide_eq_true_eq _ (d a b))) r T def equalities {n} (M : MachineTable n) : EqualityTests (widthCode n+16) (allowed M) (system n) where plain := P455EffectiveQTable.plainEq _ binary := fun i => by unfold P455BinaryProduct.Index.R split · exact markEq M (fun _ _ => .isFalse id) _ _ · exact P455EffectiveQTable.plainEq _ _ guard := fun _ => markEq M (fun _ _ => inferInstanceAs (Decidable (_=_ ∧ _=_))) _ _ edge := fun i => markEq M (P455Enum.markD i.a i.b i.c i.d) _ _ def localOps {n} (M : MachineTable n) := finiteOps (listing (indices M) (equalities M)) (P455Global.monoid M) def localPresents {n} (M : MachineTable n) : Presents (localOps M) (P455Global.monoid M) := presentation .. def ops (M : Ordinary g q) := localOps (compile (normalized M)) def presents (M : Ordinary g q) : Presents (ops M) (P455MachineReduction.model M) := localPresents (compile (normalized M)) def output (M : Ordinary g q) := matrix (ops M) theorem output_monoid (M : Ordinary g q) : P455TableSemantics.SemigroupTable (output M) ∧ P455TableSemantics.HasUnit (output M) := P455TableSemantics.output_laws (presents M) theorem finite_basis_iff (M : Ordinary g q) : P455TableSemantics.HasBasis (output M) ↔ ¬ ∃ t, stopped M t := (P455TableSemantics.basis_iff (presents M)).trans (P455Decision.ordinary_equivalence M) /-- The finite array input is validated. A rejected code returns none. -/ def fromCode (c : Code g q) : Option Matrix := c.decode.map output theorem quoted_output (M : Ordinary g q) : fromCode (quote M)=some (output M) := by simp [fromCode,quote_decode] theorem quoted_encoded (M : Ordinary g q) : P455TableBits.parse (P455TableBits.encode (output M))=some (output M) := P455TableBits.matrix_roundtrip _ end P455Encoded end /- Begin Problem455EffectiveQRaw (from finite-semigroup-identity-bases). -/ section /- Raw first-order quotient tables. Each row is labeled by one canonical raw representative. The dense table itself contains only naturals. -/ namespace P455EffectiveQRaw open P455Quotient P455EffectiveQ P455Table P455TableProduct abbrev Raw := Option W def distinctRaw (rel : Raw → Raw → Bool) : List Raw → List Raw | [] => [] | a::xs => if xs.any (rel a) then distinctRaw rel xs else a::distinctRaw rel xs def labels (e : W → W → Bool) (T : W) := distinctRaw (relB e T) (none :: (words T).map some) def index (e : W → W → Bool) (T : W) (x : Raw) := (labels e T).findIdx fun y => relB e T x y def rows (e : W → W → Bool) (T : W) := (labels e T).map fun a => (labels e T).map fun b => index e T (mulRaw a b) theorem same (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) (a b : Raw) : relB e T a b=true ↔ cls R T a=cls R T b := (rel_iff R e correct T a b).trans ⟨fun h => Quotient.sound (s := setoid R T) h,fun h => Quotient.exact h⟩ theorem map_distinct (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) (xs : List Raw) : (distinctRaw (relB e T) xs).map (cls R T) = @distinct (Q R T) (P455EffectiveQ.decEq R e correct T) (xs.map (cls R T)) := by letI := P455EffectiveQ.decEq R e correct T induction xs with | nil => rfl | cons a xs ih => have test : xs.any (relB e T a)=true ↔ cls R T a ∈ xs.map (cls R T) := by simp only [List.any_eq_true,List.mem_map,same R e correct] exact exists_congr fun x => and_congr_right fun _ => eq_comm by_cases hx : cls R T a∈xs.map (cls R T) · simp [List.map_cons,distinctRaw,distinct,hx,test.mpr hx,ih] · have neg : xs.any (relB e T a)=false := Bool.eq_false_iff.mpr (fun h => hx (test.mp h)) simp [List.map_cons,distinctRaw,distinct,hx,neg,ih] theorem map_labels (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) : (labels e T).map (cls R T) = @distinct _ (P455EffectiveQ.decEq R e correct T) (Problem455Finite.carrier R T) := by have same : (none :: (words T).map some).map (cls R T) = Problem455Finite.carrier R T := by simp only [List.map_cons, List.map_map] rfl rw [←same] exact map_distinct R e correct T (none :: (words T).map some) theorem all_labels (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) (q : Q R T) : q ∈ (labels e T).map (cls R T) := by letI := P455EffectiveQ.decEq R e correct T rw [map_labels R e correct] exact (mem_distinct _ _).mpr (Problem455Finite.carrier_complete R T q) theorem labels_nodup (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) : ((labels e T).map (cls R T)).Nodup := by letI := P455EffectiveQ.decEq R e correct T rw [map_labels R e correct] exact nodup_distinct _ def number (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) (x : Raw) : Fin (labels e T).length := ⟨index e T x,by apply List.findIdx_lt_length_of_exists obtain ⟨y,ym,eq⟩ := List.mem_map.mp (all_labels R e correct T (cls R T x)) exact ⟨y,ym,(same R e correct T ..).mpr eq.symm⟩⟩ theorem decode_number (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) (x : Raw) : cls R T ((labels e T).get (number R e correct T x))=cls R T x := by apply ((same R e correct T ..).mp _).symm exact List.findIdx_getElem (w := (number R e correct T x).isLt) def ops (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) : FiniteOps where size := (labels e T).length one := number R e correct T (some []) mul i j := number R e correct T (mulRaw ((labels e T).get i) ((labels e T).get j)) set_option backward.isDefEq.respectTransparency false in def presentation (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) (cap : Cap R.r T) : Presents (ops R e correct T) (quotientModel R T cap) where decode i := cls R T ((labels e T).get i) one_eq := decode_number R e correct T (some []) mul_eq i j := decode_number R e correct T _ inj i j eq := by apply Fin.ext let xs := (labels e T).map (cls R T) have il : i.val < xs.length := by simpa only [xs,List.length_map] using (show i.val < (labels e T).length from i.isLt) have jl : j.val < xs.length := by simpa only [xs,List.length_map] using (show j.val < (labels e T).length from j.isLt) apply (List.getElem?_inj (l := xs) il (labels_nodup R e correct T)).mp change xs[i.val]? = xs[j.val]? rw [List.getElem?_eq_getElem il,List.getElem?_eq_getElem jl] exact congrArg some (by simpa [xs] using eq) surj a := by obtain ⟨v,vm,h⟩ := List.mem_map.mp (all_labels R e correct T a) obtain ⟨i,hi,atI⟩ := List.getElem_of_mem vm exact ⟨⟨i,hi⟩,(congrArg (cls R T) atI).trans h⟩ private theorem tabulate (xs : List α) (f : α → β) : (List.finRange xs.length).map (fun i => f (xs.get i))=xs.map f := by apply List.ext_getElem · simp · intro i lt rt; simp theorem matrix_eq (R : Rules Nat) (e : W → W → Bool) (correct : ∀ u v,e u v=true ↔ R.step u v) (T : W) : matrix (ops R e correct T)=rows e T := by unfold matrix rows ops change (List.finRange (labels e T).length).map (fun i => (List.finRange (labels e T).length).map (fun j => index e T (mulRaw ((labels e T).get i) ((labels e T).get j)))) = _ let n := labels e T let row (a : Raw) := n.map fun b => index e T (mulRaw a b) have inner (i : Fin n.length) : (List.finRange n.length).map (fun j => index e T (mulRaw (n.get i) (n.get j))) = row (n.get i) := tabulate n (fun b => index e T (mulRaw (n.get i) b)) exact (List.map_congr_left (fun i _ => inner i)).trans (tabulate n row) end P455EffectiveQRaw end /- Begin Problem455MachineParseSelf (from finite-semigroup-identity-bases). -/ section namespace P455MachineParse open P455EffectiveMachine P455MachineCleanup P455EffectiveWriter abbrev Source := (g : Nat) × (q : Nat) × (M : Ordinary g q) × Alphabet M abbrev RawOrdinary := (g : Nat) × (q : Nat) × Ordinary g q def digits (a b : Fin g) : Bool → Fin g | false => a | true => b def mkSource (M : Ordinary g q) (a b : Fin g) : Option Source := if ok : a≠M.marker ∧ b≠M.marker ∧ a≠M.blank ∧ b≠M.blank ∧ a≠b then some ⟨g,q,M,⟨digits a b,fun v=>by cases v <;> first | exact ok.1 | exact ok.2.1, fun v=>by cases v <;> first | exact ok.2.2.1 | exact ok.2.2.2.1,ok.2.2.2.2⟩⟩ else none theorem mkSource_ok (M : Ordinary g q) (A : Alphabet M) : mkSource M (A.bit false) (A.bit true)=some ⟨g,q,M,A⟩ := by have h := And.intro (A.away false) (And.intro (A.away true) (And.intro (A.ink false) (And.intro (A.ink true) A.distinct))) rw [mkSource,dif_pos h] have e : digits (A.bit false) (A.bit true)=A.bit := funext (fun v=>by cases v <;> rfl) cases A simp_all def parseSelf (s : Bits) : Option Source := do let (a,t) ← P455TableBits.readNat s let (b,t) ← P455TableBits.readNat t let ⟨g,_q,c⟩ ← parseCode t let M ← c.decode let a' ← asFin g a let b' ← asFin g b mkSource M a' b' theorem self_roundtrip (M : Ordinary g q) (A : Alphabet M) : parseSelf (selfBits M A)=some ⟨g,q,M,A⟩ := by have readN (k : Nat) (t : Bits) : P455TableBits.readNat (unary k++t)=some (k,t) := P455TableBits.read_unary k t simp [parseSelf,selfBits,List.append_assoc,readN,code_roundtrip,quote_decode,mkSource_ok] def blankSource (s : Bits) : Option RawOrdinary := do let ⟨g,_,M,A⟩ ← parseSelf s let ⟨q,Q⟩ := diagonalInput M A return ⟨g,q,Q⟩ theorem blankSource_self (M : Ordinary g q) (A : Alphabet M) : blankSource (selfBits M A)=some ⟨g,(diagonalInput M A).1,(diagonalInput M A).2⟩ := by simp [blankSource,self_roundtrip] end P455MachineParse end /- Begin Problem455Packed (from finite-semigroup-identity-bases). -/ section namespace P455Packed open P455Table P455TableProduct P455TableFactors P455NumericProduct P455IndexedProduct open P455PaddedTiles P455FirstRewrite P455Quotient abbrev Spec := List Nat × Option (List (Nat × Nat)) structure Payload where r : Nat tags : List (List Bool) primitive : List Spec guard : List Spec edge : List Spec binary : List Spec structural : List Spec def moves (r : Nat) (tags : List (List Bool)) (marks : Option (List (Nat×Nat))) : List Nat → List Nat → Bool := match marks with | none => fun _ _ => false | some pairs => P455EffectiveQMove.moveB r tags (fun a b => decide ((a,b)∈pairs)) def factorRows (r : Nat) (tags : List (List Bool)) (s : Spec) := P455EffectiveQRaw.rows (moves r tags s.2) s.1 def serialize (p : Payload) : Matrix := let group := fun (xs : List Spec) => assemble (xs.map (factorRows p.r p.tags)) tensor (group p.primitive) (tensor (tensor (group p.guard) (group p.edge)) (tensor (group p.binary) (group p.structural))) def names {I : Type} (c : Listing I) (record : I → Spec) := letI := c.eq (distinct c.items).map record def primSpec (i : P455FirstTesters.Index r) : Spec := (i.val,none) def structSpec (i : P455StructuralProduct.Index r allow) : Spec := (i.T,none) def binSpec (i : P455BinaryProduct.Index r allow) : Spec := (i.T,if i.prof then some [] else none) def oneSpec (i : P455GuardProduct.Index r allow ts) : Spec := (i.T,some [(i.a.val,i.b.val)]) def twoSpec (i : P455EdgeProduct.Index r allow ts) : Spec := (i.T,some [(i.a.val,i.b.val),(i.c.val,i.d.val)]) def prepared {n} (M : MachineTable n) : Payload := let C := P455Encoded.indices M ⟨widthCode n+16,P455Enum.tags M,names C.primitive primSpec,names C.guard oneSpec, names C.edge twoSpec,names C.binary binSpec,names C.structural structSpec⟩ private theorem raw_correct (R : Rules Nat) (e : List Nat → List Nat → Bool) (correct : ∀ a b, e a b=true ↔ R.step a b) (T : List Nat) (cap : Cap R.r T) : Represents (P455EffectiveQRaw.rows e T) (quotientModel R T cap) := ⟨P455EffectiveQRaw.ops R e correct T,(P455EffectiveQRaw.matrix_eq R e correct T).symm, ⟨P455EffectiveQRaw.presentation R e correct T cap⟩⟩ private theorem plain (r tags) (T : List Nat) (cap : Cap r T) : Represents (factorRows r tags (T,none)) (quotientModel (P455FirstTesters.plain r) T cap) := raw_correct _ _ (fun _ _ => by simp [P455FirstTesters.plain,moves]) T cap private theorem marked {n} (M : MachineTable n) (r : Nat) (T : List Nat) (pairs : List (Nat×Nat)) (mark : Nat→Nat→Prop) (same : ∀ x y, (x,y)∈pairs ↔ mark x y) (cap : Cap r T) : Represents (factorRows r (P455Enum.tags M) (T,some pairs)) (quotientModel (Problem455Finite.rules r (allowed M) mark) T cap) := by apply raw_correct exact P455EffectiveQMove.move_iff (fun _ => P455Enum.mem_tags (M:=M)) (fun x y => (Iff.of_eq (decide_eq_true_eq)).trans (same x y)) r private theorem group {I : Type} {F : I → Type} (M : (i : I) → Model (F i)) (C : Listing I) (record : I → Spec) (r tags) (yes : ∀ i, Represents (factorRows r tags (record i)) (M i)) : Represents (assemble ((names C record).map (factorRows r tags))) (full M) := by letI := C.eq simpa only [names,List.map_map,Function.comp_def] using complete_product M (fun i => factorRows r tags (record i)) yes (distinct C.items) (nodup_distinct _) (fun i => (mem_distinct ..).mpr (C.all i)) private theorem binary_factor {n} (M : MachineTable n) (r : Nat) (i : P455BinaryProduct.Index r (allowed M)) : Represents (factorRows r (P455Enum.tags M) (binSpec i)) (quotientModel i.R i.T i.bound) := by rcases i with ⟨num,prof,cap,accepted⟩ cases prof with | false => exact plain r (P455Enum.tags M) _ cap | true => exact marked M r _ [] P455SlotSaturation.noMark (by simp [P455SlotSaturation.noMark]) cap set_option maxHeartbeats 1200000 in theorem serialize_represents {n} (M : MachineTable n) : Represents (serialize (prepared M)) (P455Global.monoid M) := by let r := widthCode n+16 let L := P455Enum.tags M let C := P455Encoded.indices M have prim : Represents (assemble ((names C.primitive primSpec).map (factorRows r L))) (P455FirstTesters.product r) := group (fun i : P455FirstTesters.Index r => quotientModel _ _ i.cap) C.primitive primSpec _ _ (fun i => plain r L i.val i.cap) have structural : Represents (assemble ((names C.structural structSpec).map (factorRows r L))) (P455StructuralProduct.product r (allowed M)) := group (fun i : P455StructuralProduct.Index r (allowed M) => quotientModel (P455FirstTesters.plain r) i.T i.cap) C.structural structSpec _ _ (fun i => plain r L i.T i.cap) have guards : Represents (assemble ((names C.guard oneSpec).map (factorRows r L))) (P455GuardProduct.product r (allowed M) (system n)) := group (fun i : P455GuardProduct.Index r (allowed M) (system n) => quotientModel i.R i.T i.cap) C.guard oneSpec _ _ (fun i => marked M r i.T _ _ (by intros; simp [P455SlotProduct.pairMark]) i.cap) have edges : Represents (assemble ((names C.edge twoSpec).map (factorRows r L))) (P455EdgeProduct.product r (allowed M) (system n)) := group (fun i : P455EdgeProduct.Index r (allowed M) (system n) => quotientModel i.R i.T i.cap) C.edge twoSpec _ _ (fun i => marked M r i.T _ _ (by intros; simp [P455EdgeProduct.marks]) i.cap) have binary : Represents (assemble ((names C.binary binSpec).map (factorRows r L))) (P455BinaryProduct.model r (allowed M)) := group (fun i : P455BinaryProduct.Index r (allowed M) => quotientModel i.R i.T i.bound) C.binary binSpec r L (binary_factor M r) have combined := represents_tensor prim (represents_tensor (represents_tensor guards edges) (represents_tensor binary structural)) dsimp only [serialize,prepared,P455Global.monoid,P455FullSingleton.model,P455MarkedRank.model] exact combined end P455Packed end /- Begin Problem455RowsPrim (from finite-semigroup-identity-bases). -/ section namespace P455RowsPrim open P455EffectiveQ P455GraphPrim P455ClassPrim open P455EffectiveQRaw (distinctRaw labels index rows) variable {A B : Type} [Primcodable A] [Primcodable B] theorem distinct {r : A → Raw → Raw → Bool} (hr : Primrec fun p : A×(Raw×Raw) => r p.1 p.2.1 p.2.2) {l : A → List Raw} (hl : Primrec l) : Primrec fun a => distinctRaw (r a) (l a) := by let h (a : A) (s : Raw × List Raw × List Raw) := if s.2.1.any (r a s.1) then s.2.2 else s.1::s.2.2 have hh : Primrec₂ h := by apply Primrec₂.mk apply Primrec.ite · change PrimrecPred (fun p : A×(Raw×List Raw×List Raw) => (p.2.2.1.any (r p.1 p.2.1))=true) have any := anyB (A := A × (Raw × List Raw × List Raw)) (B := Raw) (Primrec.fst.comp (Primrec.snd.comp Primrec.snd)) ((hr.comp (Primrec.pair (Primrec.fst.comp Primrec.fst) (Primrec.pair (Primrec.fst.comp (Primrec.snd.comp Primrec.fst)) Primrec.snd))).to₂) exact Primrec.eq.comp any (.const true) · exact Primrec.snd.comp (Primrec.snd.comp Primrec.snd) · exact Primrec.list_cons.comp (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) apply (Primrec.list_rec hl (Primrec.const []) hh).of_eq intro a induction l a with | nil => rfl | cons x xs ih => change h a (x,xs,_) = _ exact congrArg (fun acc => h a (x,xs,acc)) ih theorem labelRec {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2)) {t : A → W} (ht : Primrec t) : Primrec fun a => labels (e a) (t a) := by apply distinct (r := fun a => relB (e a) (t a)) · exact relation (A := A×(Raw×Raw)) (e := fun p => e p.1) (he.comp (Primrec.pair (Primrec.fst.comp Primrec.fst) Primrec.snd)) (ht.comp Primrec.fst) (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp Primrec.snd) · exact Primrec.list_cons.comp (.const none) (Primrec.list_map (wordPool.comp ht) (Primrec.option_some.comp₂ Primrec₂.right)) theorem indexRec {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2)) {t : A → W} {v : A → Raw} (ht : Primrec t) (hv : Primrec v) : Primrec fun a => index (e a) (t a) (v a) := by apply Primrec.list_findIdx (labelRec he ht) exact (relation (A := A×Raw) (e := fun p => e p.1) (he.comp (Primrec.pair (Primrec.fst.comp Primrec.fst) Primrec.snd)) (ht.comp Primrec.fst) (hv.comp Primrec.fst) Primrec.snd).to₂ theorem rawMul : Primrec₂ (fun x y : Raw => (show Raw from @P455Quotient.mulRaw Nat x y)) := by let f (p : Raw × Raw) (u : W) := p.2.map (fun v => u++v) have recProof : Primrec₂ f := Primrec₂.mk <| Primrec.option_map (Primrec.snd.comp Primrec.fst) ((Primrec.list_append.comp (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂) apply (Primrec.option_bind (Primrec.fst (α := Raw) (β := Raw)) recProof).of_eq rintro ⟨x,y⟩ cases x <;> cases y <;> rfl theorem rowsRec {e : A → W → W → Bool} (he : Primrec (fun x : A×(W×W) => e x.1 x.2.1 x.2.2)) {t : A → W} (ht : Primrec t) : Primrec fun a => rows (e a) (t a) := by apply Primrec.list_map (labelRec he ht) apply Primrec₂.mk apply Primrec.list_map ((labelRec he ht).comp Primrec.fst) apply Primrec₂.mk exact indexRec (A := (A×Raw)×Raw) (e := fun p => e p.1.1) (he.comp (Primrec.pair (Primrec.fst.comp (Primrec.fst.comp Primrec.fst)) Primrec.snd)) (ht.comp (Primrec.fst.comp Primrec.fst)) (rawMul.comp (Primrec.snd.comp Primrec.fst) Primrec.snd) end P455RowsPrim end /- Begin Problem455WriterProgram (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram open P455EffectiveMachine P455MachineLocal P455MachineCleanup P455EffectivePrefix P455EffectiveWriter abbrev Raw := Nat × Nat × Nat × Nat × Nat × List Nat abbrev g (m : Raw) := m.1 abbrev q (m : Raw) := m.2.1 abbrev marker (m : Raw) := m.2.2.1 abbrev blank (m : Raw) := m.2.2.2.1 abbrev start (m : Raw) := m.2.2.2.2.1 abbrev entries (m : Raw) := m.2.2.2.2.2 def incHead (l : List Nat) := (l.getD 0 0 + 1)::l.tail def readBits (bits : List Bool) : List Nat := bits.foldr (fun b l => bif b then incHead l else 0::l) [] theorem read_one (n : Nat) (b : List Bool) : readBits (unary n ++ b)=n::readBits b := by induction n with | zero => rfl | succ n ih => change incHead (readBits (unary n ++ b)) = _ rw [ih]; rfl theorem read_many (nums : List Nat) (b : List Bool) : readBits (nums.flatMap unary ++ b)=nums++readBits b := by induction nums with | nil => rfl | cons x xs ih => simp only [List.flatMap_cons,List.append_assoc,read_one,ih,List.cons_append] def rowData (M : Ordinary g0 q0) := (quote M).rows.toList.flatMap (fun row => row.toList.map (entryCode g0)) def data (M : Ordinary g0 q0) : Raw := (g0,q0,M.marker.val,M.blank.val,M.start.val,rowData M) theorem read_self (M : Ordinary g0 q0) (A : Alphabet M) : readBits (selfBits M A) = (A.bit false).val::(A.bit true).val::g0::q0::M.marker.val::M.blank.val::M.start.val::rowData M := by have hn : readBits []=[] := rfl have h := read_many (quote M).numerals [] simpa [selfBits,List.append_assoc,read_one,Code.bits,Code.numerals,quote,rowData,hn] using congrArg (fun l => (A.bit false).val::(A.bit true).val::l) h def raw (w : List Nat) : Raw := (w.getD 2 0,w.getD 3 0,w.getD 4 0,w.getD 5 0,w.getD 6 0,w.drop 7) theorem raw_self (M : Ordinary g0 q0) (A : Alphabet M) : raw (readBits (selfBits M A))=data M := by rw [read_self]; rfl /-- 0 means right, 1 means left, and 2+a writes a then moves right. -/ def script (a b : Nat) (w : List Bool) := 0 :: (w.map (fun x => (bif x then b else a)+2) ++ List.replicate (w.length+1) 1) def cmdCode : Cmd g0 → Nat | .right => 0 | .left => 1 | .putRight v => v.val+2 theorem script_spec (M : Ordinary g0 q0) (A : Alphabet M) (w : List Bool) : script (A.bit false).val (A.bit true).val w = (writer M A w).map cmdCode := by simp only [script,writer,List.map_cons,List.map_append,List.map_replicate,List.map_map,cmdCode] congr 2 apply List.map_congr_left intro b _; cases b <;> rfl def writtenSymbol (c m a : Nat) := if c<2 ∨ a=m ∨ c-2=m then a else c-2 def dir (c m a : Nat) := if c=1 then (if a=m then 1 else 0) else 2 def instr (g z a d : Nat) := 1+3*(g*z+a)+d def pushRaw (c : Nat) (m : Raw) : Raw := (g m,q m+1,marker m,blank m,q m, entries m ++ (List.range (g m)).map fun a => instr (g m) (start m) (writtenSymbol c (marker m) a) (dir c (marker m) a)) def blankRaw (bits : List Bool) := let l := readBits bits (script (l.getD 0 0) (l.getD 1 0) bits).foldr pushRaw (raw l) end P455WriterProgram end /- Begin Problem455RawReduction (from finite-semigroup-identity-bases). -/ section namespace P455RawReduction open P455FirstRewrite P455Table P455TableSemantics P455TableBits P455Encoded open P455EffectiveMachine P455MachineCleanup P455MachineParse P455EffectiveWriter def singleton : FiniteOps := ⟨1,0,fun _ _ => 0⟩ def trivialModel : Model Unit := ⟨fun _ _ => (),(),by intros; rfl,fun _ => rfl,fun _ => rfl⟩ def singletonPresents : Presents singleton trivialModel := by unfold singleton exact ⟨fun _ => (),fun i j _ => Subsingleton.elim i j,fun _ => ⟨0,rfl⟩,rfl,fun _ _ => rfl⟩ theorem singleton_based : HasBasis (matrix singleton) := by apply (basis_iff singletonPresents).mpr let rules : List (W×W) := [([0],[1])] refine ⟨rules,?_,?_⟩ · intro u v mem have same : (u,v)=([0],[1]) := List.mem_singleton.mp mem cases same exact ⟨by decide,by decide,fun _ => rfl⟩ · intro u v un vn _ let h : Nat → W := fun x => if x=0 then u else v refine .snoc (.refl u) ⟨[0],[1],[],[],h,.inl (by simp [rules]),by decide,by decide,?_,?_,?_⟩ · intro x; by_cases e : x=0 <;> simp [h,e,un,vn] · simp [h] · simp [h] def parseBlank (bits : List Bool) : Option RawOrdinary := do let ⟨g,q,c⟩ ← parseCode bits let M ← c.decode return ⟨g,q,M⟩ theorem parseBlank_quote (M : Ordinary g q) : parseBlank (quote M).bits=some ⟨g,q,M⟩ := by simp [parseBlank,code_roundtrip,quote_decode] def realizesHalt : Option RawOrdinary → Prop | none => False | some ⟨_,_,M⟩ => ∃ t, stopped M t def makeTable : Option RawOrdinary → Matrix | none => matrix singleton | some ⟨_,_,M⟩ => output M theorem makeTable_laws (source : Option RawOrdinary) : SemigroupTable (makeTable source) ∧ HasUnit (makeTable source) := by rcases source with _|⟨_,_,M⟩ · exact output_laws singletonPresents · exact output_monoid M theorem makeTable_basis (source : Option RawOrdinary) : HasBasis (makeTable source) ↔ ¬ realizesHalt source := by rcases source with _|⟨_,_,M⟩ · exact ⟨fun _ => id,fun _ => singleton_based⟩ · exact finite_basis_iff M def blankTable (bits : List Bool) := makeTable (parseBlank bits) def blankBits (bits : List Bool) := encode (blankTable bits) def diagonalTable (bits : List Bool) := makeTable (blankSource bits) def diagonalBits (bits : List Bool) := encode (diagonalTable bits) theorem bit_roundtrip (source : Option RawOrdinary) : parse (encode (makeTable source))=some (makeTable source) := by rcases source with _|⟨_,_,M⟩ · exact matrix_roundtrip _ · exact quoted_encoded M /-- For every raw input, the output bytes parse as an associative monoid table and give the claimed answer on the ordinary semigroup signature. -/ theorem exact_blank (bits : List Bool) : parse (blankBits bits)=some (blankTable bits) ∧ SemigroupTable (blankTable bits) ∧ HasUnit (blankTable bits) ∧ (HasBasis (blankTable bits) ↔ ¬ realizesHalt (parseBlank bits)) := ⟨bit_roundtrip _,(makeTable_laws _).1,(makeTable_laws _).2,makeTable_basis _⟩ theorem blank_matrix_iso (M : Ordinary g q) : blankTable (quote M).bits = matrix (ops M) ∧ Nonempty (Presents (ops M) (P455MachineReduction.model M)) := ⟨by simp [blankTable,parseBlank_quote,makeTable,output],⟨presents M⟩⟩ theorem exact_self (M : Ordinary g q) (A : Alphabet M) : HasBasis (diagonalTable (selfBits M A)) ↔ ¬SelfHalt M A := by rw [diagonalTable,blankSource_self,makeTable,finite_basis_iff,diagonal_input_iff] end P455RawReduction end /- Begin Problem455WriterTileData (from finite-semigroup-identity-bases). -/ section /- Numerical data consumed by the tile catalogue. The local transition list is row-major in (left neighbour, centre symbol, right neighbour) order. -/ namespace P455WriterTiles open P455PaddedTiles abbrev MachineData := Nat × List Bool × Nat × Nat × Nat × List (Option Nat) def size (D : MachineData) := D.1 def marker (D : MachineData) (c : Nat) := D.2.1[c]?.getD false def initial (D : MachineData) (left : Bool) := if left then D.2.2.2.1 else D.2.2.1 def accept (D : MachineData) := D.2.2.2.2.1 def address (n l c r : Nat) := (l*n+c)*(n+1)+r def update (D : MachineData) (l c r : Nat) : Option Nat := D.2.2.2.2.2[address D.1 l c r]?.getD none structure Models (D : MachineData) {n} (M : MachineTable n) : Prop where dim : size D = n marks : ∀ c, marker D c.val = M.marker c start : ∀ b, initial D b = (M.initial b).val final : accept D = M.accept.val step : ∀ l c r, update D (letter l) c.val (letter r) = (M.next l c r).map Fin.val end P455WriterTiles end /- Begin Problem455SerializePrim (from finite-semigroup-identity-bases). -/ section /- Certify the actual table serializer on arbitrary first-order records. This theorem takes the catalogue as input. -/ namespace P455SerializePrim open P455Packed abbrev Tags := List (List Bool) abbrev Marks := List (Nat × Nat) abbrev W := List Nat abbrev Data := Nat × Tags × List Spec × List Spec × List Spec × List Spec × List Spec def asPayload (x : Data) : Payload := ⟨x.1, x.2.1, x.2.2.1, x.2.2.2.1, x.2.2.2.2.1, x.2.2.2.2.2.1, x.2.2.2.2.2.2⟩ def ofPayload (p : Payload) : Data := (p.r, p.tags, p.primitive, p.guard, p.edge, p.binary, p.structural) theorem as_of (p : Payload) : asPayload (ofPayload p) = p := rfl variable {A : Type} [Primcodable A] theorem move {r : A → Nat} {tags : A → Tags} {mark : A → Option Marks} {u v : A → W} (hr : Primrec r) (ht : Primrec tags) (hm : Primrec mark) (hu : Primrec u) (hv : Primrec v) : Primrec fun a => moves (r a) (tags a) (mark a) (u a) (v a) := by let h (a : A) (ps : Marks) := P455EffectiveQMove.moveB (r a) (tags a) (fun x y => decide ((x,y) ∈ ps)) (u a) (v a) have m : Primrec₂ h := Primrec₂.mk (P455FrameProof.literalMove (hr.comp Primrec.fst) (ht.comp Primrec.fst) Primrec.snd (hu.comp Primrec.fst) (hv.comp Primrec.fst)) exact (Primrec.option_casesOn hm (Primrec.const false) m).of_eq (fun a => by cases e : mark a <;> simp [moves,e,h]) theorem factor {r : A → Nat} {tags : A → Tags} {s : A → Spec} (hr : Primrec r) (ht : Primrec tags) (hs : Primrec s) : Primrec fun a => factorRows (r a) (tags a) (s a) := by apply P455RowsPrim.rowsRec (e := fun a => moves (r a) (tags a) (s a).2) · exact move (hr.comp Primrec.fst) (ht.comp Primrec.fst) ((Primrec.snd.comp hs).comp Primrec.fst) (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp Primrec.snd) · exact Primrec.fst.comp hs theorem group {r : A → Nat} {tags : A → Tags} {s : A → List Spec} (hr : Primrec r) (ht : Primrec tags) (hs : Primrec s) : Primrec fun a => P455NumericProduct.assemble ((s a).map (factorRows (r a) (tags a))) := P455NumericProductPrim.assemble'.comp (Primrec.list_map hs (Primrec₂.mk (factor (hr.comp Primrec.fst) (ht.comp Primrec.fst) Primrec.snd))) theorem serialize : Primrec fun x : Data => P455Packed.serialize (asPayload x) := by have r : Primrec fun x : Data => x.1 := Primrec.fst have s := Primrec.snd (α := Nat) (β := Tags × List Spec × List Spec × List Spec × List Spec × List Spec) have tags := Primrec.fst.comp s have ss := Primrec.snd.comp s have gs := Primrec.snd.comp ss have es := Primrec.snd.comp gs have bs := Primrec.snd.comp es exact P455NumericProductPrim.tensor'.comp (group r tags (Primrec.fst.comp ss)) (P455NumericProductPrim.tensor'.comp (P455NumericProductPrim.tensor'.comp (group r tags (Primrec.fst.comp gs)) (group r tags (Primrec.fst.comp es))) (P455NumericProductPrim.tensor'.comp (group r tags (Primrec.fst.comp bs)) (group r tags (Primrec.snd.comp bs)))) theorem bits : Primrec fun x : Data => P455TableBits.encode (P455Packed.serialize (asPayload x)) := P455NumericProductPrim.encode.comp serialize theorem bits_after_catalogue {p : A → Payload} (h : Computable (fun a => ofPayload (p a))) : Computable (fun a => P455TableBits.encode (P455Packed.serialize (p a))) := by simpa only [Function.comp_def,as_of] using bits.to_comp.comp h end P455SerializePrim end /- Begin Problem455WriterBlank (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram open P455EffectiveMachine P455MachineLocal P455MachineCleanup P455EffectivePrefix P455EffectiveWriter theorem indices_ofFn {α : Type} (f : Fin n → α) : (Vector.ofFn f).toList = (List.finRange n).map f := by apply List.ext_getElem (by simp) intro i hi hj simp [Vector.toList_ofFn] def row (M : Ordinary g0 q0) (z : Fin q0) := (List.finRange g0).map (fun a => entryCode g0 (M.delta z a)) theorem rows_spec (M : Ordinary g0 q0) : rowData M = (List.finRange q0).flatMap (row M) := by simp only [rowData,quote,indices_ofFn,List.flatMap_map,Function.comp_def,List.map_map] rfl theorem cols (n : Nat) : List.range n=(List.finRange n).map Fin.val := by apply List.ext_getElem (by simp); intros; simp theorem code_write (cmd : Cmd g0) (m a : Fin g0) : writtenSymbol (cmdCode cmd) m.val a.val = (write m cmd a).val := by cases cmd with | right => simp [writtenSymbol,cmdCode,write] | left => simp [writtenSymbol,cmdCode,write] | putRight v => simp only [writtenSymbol,cmdCode,Nat.add_sub_cancel,write] by_cases ea : a=m <;> by_cases ev : v=m <;> simp_all [Fin.ext_iff] <;> omega theorem code_motion (cmd : Cmd g0) (m a : Fin g0) : dir (cmdCode cmd) m.val a.val=dirCode (motion m cmd a) := by cases cmd with | right => rfl | left => by_cases ea : a=m <;> simp_all [dir,cmdCode,motion,dirCode,Fin.ext_iff] | putRight v => simp [dir,cmdCode,motion,dirCode] theorem entry_lift (i : Option (Ins (Fin g0) (Fin q0))) : entryCode g0 (i.map liftIns) = entryCode g0 i := by cases i <;> rfl theorem push_data (M : Ordinary g0 q0) (c : Cmd g0) : pushRaw (cmdCode c) (data M)=data (push M c) := by have low (s : Fin q0) : row (push M c) s.castSucc=row M s := by unfold row; apply List.map_congr_left intro a _ change entryCode _ ((push M c).delta (P455EffectivePrefix.old s) a)=_ rw [old_ins,entry_lift] have top : row (push M c) (Fin.last q0)= (List.range g0).map (fun a => instr g0 M.start.val (writtenSymbol (cmdCode c) M.marker.val a) (dir (cmdCode c) M.marker.val a)) := by unfold row rw [cols]; simp only [List.map_map,Function.comp_def] apply List.map_congr_left; intro a _ change entryCode _ ((push M c).delta (head q0) a)=_ rw [head_ins,code_write,code_motion]; rfl have content : rowData (push M c)=rowData M++ (List.range g0).map (fun a => instr g0 M.start.val (writtenSymbol (cmdCode c) M.marker.val a) (dir (cmdCode c) M.marker.val a)) := by rw [rows_spec,rows_spec,List.finRange_succ_last] simp [List.flatMap_append,List.flatMap_map,Function.comp_def,low,top] exact congrArg (fun xs => (g0,q0+1,M.marker.val,M.blank.val,q0,xs)) content.symm theorem install_data (M : Ordinary g0 q0) (cs : List (Cmd g0)) : (cs.map cmdCode).foldr pushRaw (data M)=data (install M cs).2 := by induction cs with | nil => rfl | cons c cs ih => simp only [List.map_cons,List.foldr_cons,ih,push_data,install] theorem blank_self (M : Ordinary g0 q0) (A : Alphabet M) : blankRaw (selfBits M A)=data (diagonalInput M A).2 := by dsimp only [blankRaw] rw [raw_self] have eq := read_self M A rw [eq] change (script (A.bit false).val (A.bit true).val (selfBits M A)).foldr pushRaw (data M)=_ rw [script_spec,install_data] rfl end P455WriterProgram end /- Begin Problem455Operational (from finite-semigroup-identity-bases). -/ section namespace P455Operational open P455EffectiveMachine P455MachineCleanup P455EffectiveChain P455RelabeledChain open P455RawReduction P455TableBits P455TableSemantics def DecidesTable (D : Ordinary g r) (B : Alphabet D) (ans : Fin r → Bool) := Separates (Answers D B ans) /-- A single transducer, independent of all readers, including their alphabet sizes and state names. Only its behavior on self codes is needed. -/ def WritesSelf (W : Ordinary g q) (A O : Alphabet W) := ∀ {h r} (P : Ordinary h r) (B : Alphabet P), Delivers W A (selfBits P B) W O (diagonalBits (selfBits P B)) private theorem negate_answer {b : Bool} {H : Prop} (spec : b=true ↔ ¬H) : (!b)=true ↔ H := by classical cases b <;> simp_all /-- No ordinary binary-input machine decides the coded inverse image. This statement by itself concerns machine strings, not the table language on arbitrary multiplication arrays. -/ theorem no_diagonal_reader (D : Ordinary g r) (B : Alphabet D) (ans : Fin r → Bool) : ¬ (∀ x : List Bool, ∃ b, Answers D B ans x b ∧ (b=true ↔ HasBasis (diagonalTable x))) := by intro all apply no_self_decider D B (fun z => !(ans z)) intro h s P A obtain ⟨b,⟨t,stop,outcome⟩,spec⟩ := all (selfBits P A) refine ⟨t,stop,?_⟩ change (!(ans (follow D (inputConfig D B (selfBits P A)) t).state))=true ↔ SelfHalt P A rw [outcome] exact negate_answer (spec.trans (exact_self P A)) theorem no_table_decider_of_writer (W : Ordinary g q) (A O : Alphabet W) (writes : WritesSelf W A O) (D : Ordinary h r) (B : Alphabet D) (ans : Fin r → Bool) : ¬ DecidesTable D B ans := by intro reads let C := combined W O D B let I := inputs W A O D B apply no_self_decider C I (fun z => !(P455EffectiveChain.out q ans z)) intro h' r' P X let x := selfBits P X obtain ⟨b,reading,spec⟩ := reads (diagonalTable x) (makeTable_laws _).1 have run := answers_combined W A O D B ans (writes P X) reading obtain ⟨t,stop,outcome⟩ := run refine ⟨t,stop,?_⟩ change (!(P455EffectiveChain.out q ans (follow (combined W O D B) (inputConfig (combined W O D B) (inputs W A O D B) (selfBits P X)) t).state))=true ↔ SelfHalt P X rw [outcome] exact negate_answer (spec.trans (exact_self P X)) /-- All that remains for the operational undecidability conclusion is existence of one finite writer for the indicated fixed transformation. -/ def WriterExists := ∃ (g q : Nat) (W : Ordinary g q) (A O : Alphabet W), WritesSelf W A O def TableDeciderExists := ∃ (g q : Nat) (D : Ordinary g q) (B : Alphabet D) (ans : Fin q → Bool), DecidesTable D B ans theorem operational_implication : WriterExists → ¬TableDeciderExists := by rintro ⟨_,_,W,A,O,writes⟩ ⟨_,_,D,B,ans,reads⟩ exact no_table_decider_of_writer W A O writes D B ans reads end P455Operational end /- Begin Problem455PureSemigroup (from finite-semigroup-identity-bases). -/ section /- No background axiom is built into Equational. Associativity is added to the finite rule list by its single multiplication-only identity. -/ namespace P455PureSemigroup open P455Table P455TableSemantics P455BinaryTerms P455BinaryBasis inductive Equational (G : Term → Term → Prop) : Term → Term → Prop | refl (x) : Equational G x x | symm : Equational G x y → Equational G y x | trans : Equational G x y → Equational G y z → Equational G x z | gen : G x y → Equational G x y | mul : Equational G x y → Equational G z t → Equational G (.mul x z) (.mul y t) | subst (f) : Equational G x y → Equational G (inst f x) (inst f y) def assocPair : Term × Term := (.mul (.mul (.var 0) (.var 1)) (.var 2),.mul (.var 0) (.mul (.var 1) (.var 2))) def Basis (T : Matrix) := ∃ rules : List (Term × Term), (∀ u v, (u,v)∈rules → ValidTerm T u v) ∧ ∀ u v, ValidTerm T u v → Equational (fun x y => (x,y)∈rules) u v theorem forget {G} {u v} (p : Equational G u v) : Proof G u v := by induction p with | refl => exact .refl _ | symm _ ih => exact .symm ih | trans _ _ ih ik => exact .trans ih ik | gen m => exact .gen m | mul _ _ ih ik => exact .mul ih ik | subst f _ ih => exact .subst f ih theorem explicit_assoc (rs : List (Term × Term)) {u v} (p : Proof (fun x y => (x,y)∈rs) u v) : Equational (fun x y => (x,y)∈assocPair::rs) u v := by induction p with | refl => exact .refl _ | symm _ ih => exact .symm ih | trans _ _ ih ik => exact .trans ih ik | gen m => exact .gen (List.mem_cons_of_mem _ m) | mul _ _ ih ik => exact .mul ih ik | subst f _ ih => exact .subst f ih | assoc x y z => let f (i : Nat) := if i=0 then x else if i=1 then y else z have law : Equational (fun s t => (s,t)∈assocPair::rs) assocPair.1 assocPair.2 := .gen List.mem_cons_self exact .subst f law theorem basis_iff {T : Matrix} (good : SemigroupTable T) : Basis T ↔ P455TableSemantics.HasBasis T := by rw [←basis_iff_words good] constructor · rintro ⟨rs,s,all⟩; exact ⟨rs,s,fun u v h => forget (all u v h)⟩ · rintro ⟨rs,s,all⟩ refine ⟨assocPair::rs,?_,fun u v h => explicit_assoc rs (all u v h)⟩ intro u v mem rcases List.mem_cons.mp mem with first|old · cases first intro f bounded exact good.2.2 (f 0) (f 1) (f 2) (bounded 0) (bounded 1) (bounded 2) · exact s _ _ old theorem raw_basis (s : List Bool) : Basis (P455RawReduction.blankTable s) ↔ ¬ P455RawReduction.realizesHalt (P455RawReduction.parseBlank s) := (basis_iff (P455RawReduction.exact_blank s).2.1).trans (P455RawReduction.exact_blank s).2.2.2 end P455PureSemigroup end /- Begin Problem455WriterTiles (from finite-semigroup-identity-bases). -/ section /- Primitive-recursive tag enumeration for the literal numerical local rule. -/ namespace P455WriterTiles open P455PaddedTiles abbrev TileData := Bool × Bool × Bool × Bool × Bool × Bool × Nat × Nat × Nat × Nat def raw (p : Tile n) : TileData := (p.left,p.right,p.top,p.bottom,p.oddRow,p.oddColumn,letter p.l,p.c.val,letter p.r,p.b.val) def choices (xs : List X) (ys : List Y) : List (X × Y) := xs.flatMap fun x => ys.map fun y => (x,y) theorem map_choices (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) := by simp only [choices,List.map_flatMap,List.map_map,Function.comp_def] theorem choicesRec {A X Y : Type} [Primcodable A] [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) := by apply Primrec.list_flatMap hx apply Primrec₂.mk apply Primrec.list_map (hy.comp Primrec.fst) exact (Primrec.pair (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂ def options (n : Nat) := 0 :: (List.range n).map Nat.succ def pool (n : Nat) : List TileData := let b := [false,true] let s := List.range n let o := options n choices b (choices b (choices b (choices b (choices b (choices b (choices o (choices s (choices o s)))))))) theorem optionsRec : Primrec options := Primrec.list_cons.comp (.const 0) (Primrec.list_map Primrec.list_range (Primrec.succ.comp Primrec.snd).to₂) theorem poolRec : Primrec pool := by have b : Primrec (fun _ : Nat => [false,true]) := Primrec.const _ have o := optionsRec have s := Primrec.list_range exact choicesRec b (choicesRec b (choicesRec b (choicesRec b (choicesRec b (choicesRec b (choicesRec o (choicesRec s (choicesRec o s)))))))) theorem map_raw (n : Nat) : ((P455Enum.tiles n).list.map raw) = pool n := by have op : options n = (P455Enum.options (P455Enum.fins n)).list.map letter := by simp only [options,P455Enum.options,P455Enum.fins,List.map_cons,List.map_map,letter] rw [←p455MapFinRange,List.map_map] rfl unfold pool rw [op,←p455MapFinRange] simp only [P455Enum.tiles,P455Enum.bools,P455Enum.fins,choices,List.map_flatMap,List.map_map, List.flatMap_map,List.flatMap_assoc,Function.comp_def,raw] def tokenN (n k : Nat) := digit (n+1) k def rawCode (n : Nat) (p : TileData) := p.1 :: p.2.1 :: p.2.2.1 :: p.2.2.2.1 :: p.2.2.2.2.1 :: p.2.2.2.2.2.1 :: (tokenN n p.2.2.2.2.2.2.1 ++ (tokenN n (p.2.2.2.2.2.2.2.1+1) ++ (tokenN n p.2.2.2.2.2.2.2.2.1 ++ tokenN n (p.2.2.2.2.2.2.2.2.2+1)))) theorem code_raw (p : Tile n) : rawCode n (raw p) = code p := rfl def eligible (D : MachineData) (p : TileData) : Prop := let (left,right,top,bottom,oddRow,oddColumn,l,c,r,b) := p update D l c r = some b ∧ left=decide (l=0) ∧ right=decide (r=0) ∧ marker D c=left ∧ (left=true → oddColumn=false) ∧ (top=true → oddRow=false ∧ c=initial D left) ∧ (bottom=true → left=true → c=accept D) instance eligibleDec (D : MachineData) (p : TileData) : Decidable (eligible D p) := by unfold eligible; infer_instance set_option backward.isDefEq.respectTransparency false in theorem eligible_raw {D : MachineData} {M : MachineTable n} (h : Models D M) (p : Tile n) : eligible D (raw p) ↔ Admitted M p := by have none (s : Option (Fin n)) : decide (letter s=0) = s.isNone := by cases s <;> simp [letter] have step : (M.next p.l p.c p.r).map Fin.val = some p.b.val ↔ M.next p.l p.c p.r = some p.b := by cases e : M.next p.l p.c p.r <;> simp [Fin.ext_iff] simp only [eligible,raw,Admitted,h.step,h.marks,h.start,h.final,step,Fin.ext_iff] rw [none p.l, none p.r] def tags (D : MachineData) := ((pool (size D)).filter (eligible D)).map (rawCode (size D)) theorem tags_correct {D : MachineData} {M : MachineTable n} (h : Models D M) : tags D = P455Enum.tags M := by unfold tags P455Enum.tags rw [h.dim,←map_raw,List.filter_map,List.map_map] have same : ((P455Enum.tiles n).list.filter (fun p => decide (eligible D (raw p)))) = ((P455Enum.tiles n).list.filter (Admitted M)) := by apply List.filter_congr intro p _ exact Bool.eq_iff_iff.mpr (by simpa using eligible_raw h p) simpa only [Function.comp_def,code_raw] using congrArg (List.map code) same end P455WriterTiles end /- Begin Problem455WriterNorm (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram open P455EffectiveMachine P455MachineLocal P455MachineCleanup theorem flat_lookup {A B : Type} (f : A → List B) (k : Nat) (len : ∀ x, (f x).length = k) (xs : List A) (i j : Nat) (hi : i < xs.length) (hj : j < k) : (xs.flatMap f)[i*k+j]? = (f xs[i])[j]? := by induction xs generalizing i with | nil => simp at hi | cons x xs ih => cases i with | zero => simp only [List.flatMap_cons,Nat.zero_mul,Nat.zero_add,List.getElem_cons_zero] exact List.getElem?_append_left (by simpa [len] using hj) | succ i => have hi' : i decide have hp₁ : (1+3*(ng*i.state.val+i.symbol.val)+dirCode i.dir)-1=3*(ng*i.state.val+i.symbol.val)+dirCode i.dir := by omega simp [unpack,entryCode,hp₁,Nat.mul_add_div (by decide : 0<3),Nat.div_eq_of_lt hd,Nat.mul_add_mod, Nat.mod_eq_of_lt hd,Nat.mul_add_div hp,Nat.div_eq_of_lt i.symbol.isLt,Nat.mod_eq_of_lt i.symbol.isLt,numIns] def normalizedIns (m : Raw) (z a : Nat) : Triple := if z simp [s] at e; simp [e,entryCode,numIns,cleanState,dirCode] | some i => have N : entryCode ng (some i)≠0 := by simp [entryCode] <;> omega rw [if_neg N,unpack_some]; simp [s] at e; simp [e,numIns,extend,old] · by_cases k : z.val=nq <;> by_cases e : a=M.marker <;> simp [normalizedIns,data,P455MachineCleanup.trans,q,g,marker,entries,h,k,e,Fin.ext_iff.mp, numIns,cleanState,acceptState,dirCode,← Fin.ext_iff] end P455WriterProgram end /- Begin Problem455WriterProgramPrim (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram namespace Cert open Primrec variable {X : Type} [Primcodable X] theorem g' : Primrec g := Primrec.fst theorem q' : Primrec q := Primrec.fst.comp Primrec.snd theorem marker' : Primrec marker := Primrec.fst.comp (Primrec.snd.comp Primrec.snd) theorem blank' : Primrec blank := Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) theorem start' : Primrec start := Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd))) theorem entries' : Primrec entries := Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd))) theorem get (l : X → List Nat) (hl : Primrec l) (n : Nat) : Primrec fun x => (l x).getD n 0 := (Primrec.list_getD 0).comp hl (Primrec.const n) theorem incHead' : Primrec incHead := Primrec.list_cons.comp (Primrec.nat_add.comp (get _ Primrec.id 0) (Primrec.const 1)) Primrec.list_tail theorem readBits' : Primrec readBits := by apply Primrec.list_foldr (h:=fun (_ : List Bool) (p : Bool × List Nat) => bif p.1 then incHead p.2 else 0::p.2) (Primrec.id (α:=List Bool)) (Primrec.const ([] : List Nat)) exact (Primrec.cond (Primrec.fst.comp Primrec.snd) (incHead'.comp (Primrec.snd.comp Primrec.snd)) (Primrec.list_cons.comp (Primrec.const 0) (Primrec.snd.comp Primrec.snd))).to₂ theorem drop' (n : Nat) : Primrec fun l : List Nat => l.drop n := by induction n with | zero => exact Primrec.id | succ n ih => exact (Primrec.list_tail.comp ih).of_eq fun l => List.tail_drop theorem raw' : Primrec raw := (get _ Primrec.id 2).pair ((get _ Primrec.id 3).pair ((get _ Primrec.id 4).pair ((get _ Primrec.id 5).pair ((get _ Primrec.id 6).pair (drop' 7))))) theorem ones : Primrec fun n : Nat => List.replicate n (1 : Nat) := (Primrec.list_map Primrec.list_range (Primrec₂.const 1)).of_eq (fun _ => by simp [List.map_const']) theorem script' {w : X → List Bool} {a b : X → Nat} (ha : Primrec a) (hb : Primrec b) (hw : Primrec w) : Primrec fun x => script (a x) (b x) (w x) := Primrec.list_cons.comp (Primrec.const 0) (Primrec.list_append.comp (Primrec.list_map hw (Primrec.nat_add.comp (Primrec.cond Primrec.snd (hb.comp Primrec.fst) (ha.comp Primrec.fst)) (Primrec.const 2)).to₂) (ones.comp (Primrec.nat_add.comp (Primrec.list_length.comp hw) (Primrec.const 1)))) theorem written' {c m a : X → Nat} (hc : Primrec c) (hm : Primrec m) (ha : Primrec a) : Primrec fun x => writtenSymbol (c x) (m x) (a x) := Primrec.ite ((Primrec.nat_lt.comp hc (Primrec.const 2)).or ((Primrec.eq.comp ha hm).or (Primrec.eq.comp (Primrec.nat_sub.comp hc (Primrec.const 2)) hm))) ha (Primrec.nat_sub.comp hc (Primrec.const 2)) theorem dir' {c m a : X → Nat} (hc : Primrec c) (hm : Primrec m) (ha : Primrec a) : Primrec fun x => dir (c x) (m x) (a x) := Primrec.ite (Primrec.eq.comp hc (Primrec.const 1)) (Primrec.ite (Primrec.eq.comp ha hm) (Primrec.const 1) (Primrec.const 0)) (Primrec.const 2) theorem instr' {ng z a d : X → Nat} (hg : Primrec ng) (hz : Primrec z) (ha : Primrec a) (hd : Primrec d) : Primrec fun x => instr (ng x) (z x) (a x) (d x) := Primrec.nat_add.comp (Primrec.nat_add.comp (Primrec.const 1) (Primrec.nat_mul.comp (Primrec.const 3) (Primrec.nat_add.comp (Primrec.nat_mul.comp hg hz) ha))) hd theorem push' : Primrec₂ pushRaw := by apply Primrec₂.mk have m : Primrec fun p : Nat × Raw => p.2 := Primrec.snd have aux : Primrec fun p : (Nat × Raw) × Nat => p.1.2 := m.comp Primrec.fst have c : Primrec fun p : (Nat × Raw) × Nat => p.1.1 := Primrec.fst.comp Primrec.fst exact (g'.comp m).pair ((Primrec.nat_add.comp (q'.comp m) (Primrec.const 1)).pair ((marker'.comp m).pair ((blank'.comp m).pair ((q'.comp m).pair (Primrec.list_append.comp (entries'.comp m) (Primrec.list_map (Primrec.list_range.comp (g'.comp m)) (instr' (g'.comp aux) (start'.comp aux) (written' c (marker'.comp aux) Primrec.snd) (dir' c (marker'.comp aux) Primrec.snd)).to₂)))))) theorem blankRaw' : Primrec blankRaw := by apply Primrec.list_foldr (h:=fun (_ : List Bool) (p : Nat × Raw) => pushRaw p.1 p.2) (script' (get _ readBits' 0) (get _ readBits' 1) Primrec.id) (raw'.comp readBits') exact (push'.comp (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp Primrec.snd)).to₂ end Cert end P455WriterProgram end /- Begin Problem455AnyPresentation (from finite-semigroup-identity-bases). -/ section namespace P455AnyPresentation open P455MachineCleanup P455MachineTable P455EffectiveMachine P455EffectiveChain open P455RelabeledChain P455EffectiveWriter P455Table P455TableBits P455TableSemantics open P455Operational /-- The one finite writer may use any presentation of the model on each well-formed self input. No agreement with the ordering in `ops` is required. -/ def WritesPresentation (W : Ordinary g q) (A O : Alphabet W) := ∀ {k s} (P : Ordinary k s) (B : Alphabet P), ∃ X : FiniteOps, Nonempty (Presents X (P455MachineReduction.model (diagonalInput P B).2)) ∧ Delivers W A (selfBits P B) W O (encode (matrix X)) theorem exact_writer_suffices (W : Ordinary g q) (A O : Alphabet W) (writes : WritesSelf W A O) : WritesPresentation W A O := by intro k s P B refine ⟨P455Encoded.ops (diagonalInput P B).2,⟨P455Encoded.presents _⟩,?_⟩ have output_eq : P455RawReduction.diagonalBits (selfBits P B)= encode (matrix (P455Encoded.ops (diagonalInput P B).2)) := by unfold P455RawReduction.diagonalBits P455RawReduction.diagonalTable rw [P455MachineParse.blankSource_self] rfl rw [←output_eq] exact writes P B /-- Direct complement diagonal. The trap runs forever on a negative verdict. Its own halting is consequently equivalent to the positive verdict. -/ theorem no_table_decider (W : Ordinary g q) (A O : Alphabet W) (writes : WritesPresentation W A O) (D : Ordinary h r) (B : Alphabet D) (ans : Fin r → Bool) : ¬ DecidesTable D B ans := by intro reads let C := combined W O D B let I := inputs W A O D B let negate : Fin (q+r) → Bool := fun z => !(P455EffectiveChain.out q ans z) let P := trap C negate let J := P455EffectiveMachine.liftAlphabet C I negate let x := selfBits P J let c := inputConfig C I x obtain ⟨X,⟨pres⟩,delivers⟩ := writes P J obtain ⟨b,reading,spec⟩ := reads (matrix X) (output_laws pres).1 obtain ⟨t,stop,outcome⟩ := answers_combined W A O D B ans delivers reading change instruction C (follow C c t)=none at stop change P455EffectiveChain.out q ans (follow C c t).state=b at outcome have self : SelfHalt P J ↔ b=true := by change HALT (trap C negate) c ↔ b=true rw [halt_trap_iff C negate c stop] change (!(P455EffectiveChain.out q ans (follow C c t).state))=false ↔ b=true rw [outcome] cases b <;> decide have flip : b=true ↔ ¬ SelfHalt P J := spec.trans ((basis_iff pres).trans (diagonal_basis P J)) have no : ¬ SelfHalt P J := fun v => flip.mp (self.mp v) v exact no (self.mpr (flip.mpr no)) end P455AnyPresentation end /- Begin Problem455WriterEdgeTypes (from finite-semigroup-identity-bases). -/ section namespace P455WriterEdge open P455Witness variable {X : Type} [Primcodable X] def nodeCode : Node ≃ Nat × Nat × List Bool where toFun x := (x.owner,x.mate,x.tag) invFun p := ⟨p.1,p.2.1,p.2.2⟩ left_inv := by intro x; cases x; rfl right_inv := by rintro ⟨owner,mate,tag⟩; rfl instance : Primcodable Node := Primcodable.ofEquiv _ nodeCode theorem nodeCodeRec : Primrec nodeCode := Primrec.of_equiv theorem ownerRec : Primrec Node.owner := (Primrec.fst.comp nodeCodeRec) theorem mateRec : Primrec Node.mate := (Primrec.fst.comp (Primrec.snd.comp nodeCodeRec)) theorem tagRec : Primrec Node.tag := (Primrec.snd.comp (Primrec.snd.comp nodeCodeRec)) theorem mkNodeRec {x0 : X → Nat} {x1 : X → Nat} {x2 : X → List Bool} (h0 : Primrec x0) (h1 : Primrec x1) (h2 : Primrec x2) : Primrec (fun u => Node.mk (x0 u) (x1 u) (x2 u)) := (Primrec.of_equiv_symm (e:=nodeCode)).comp (h0.pair (h1.pair h2)) def dirCode : Dir ≃ Bool × Bool where toFun | .right => (false,false) | .left => (false,true) | .down => (true,false) | .up => (true,true) invFun | (false,false) => .right | (false,true) => .left | (true,false) => .down | (true,true) => .up left_inv := by intro d; cases d <;> rfl right_inv := by rintro ⟨a,b⟩; cases a <;> cases b <;> rfl instance : Primcodable Dir := Primcodable.ofEquiv _ dirCode theorem dirCodeRec : Primrec dirCode := Primrec.of_equiv def funcCode : FunctionalityCertificate ≃ Node × Bool × Node × Node × Dir × Bool where toFun x := (x.anchor,x.bit,x.b,x.c,x.dir,x.distinguishMate) invFun p := ⟨p.1,p.2.1,p.2.2.1,p.2.2.2.1,p.2.2.2.2.1,p.2.2.2.2.2⟩ left_inv := by intro x; cases x; rfl right_inv := by rintro ⟨anchor,bit,b,c,dir,distinguishMate⟩; rfl instance : Primcodable FunctionalityCertificate := Primcodable.ofEquiv _ funcCode theorem funcCodeRec : Primrec funcCode := Primrec.of_equiv theorem funcAnchorRec : Primrec FunctionalityCertificate.anchor := (Primrec.fst.comp funcCodeRec) theorem funcBitRec : Primrec FunctionalityCertificate.bit := (Primrec.fst.comp (Primrec.snd.comp funcCodeRec)) theorem funcBRec : Primrec FunctionalityCertificate.b := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp funcCodeRec))) theorem funcCRec : Primrec FunctionalityCertificate.c := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp funcCodeRec)))) theorem funcDirRec : Primrec FunctionalityCertificate.dir := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp funcCodeRec))))) theorem funcDistinguishMateRec : Primrec FunctionalityCertificate.distinguishMate := (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp funcCodeRec))))) theorem mkFuncRec {x0 : X → Node} {x1 : X → Bool} {x2 : X → Node} {x3 : X → Node} {x4 : X → Dir} {x5 : X → Bool} (h0 : Primrec x0) (h1 : Primrec x1) (h2 : Primrec x2) (h3 : Primrec x3) (h4 : Primrec x4) (h5 : Primrec x5) : Primrec (fun u => FunctionalityCertificate.mk (x0 u) (x1 u) (x2 u) (x3 u) (x4 u) (x5 u)) := (Primrec.of_equiv_symm (e:=funcCode)).comp (h0.pair (h1.pair (h2.pair (h3.pair (h4.pair h5))))) def edgeCode : EdgeCertificate ≃ Node × Node × Node × Node × Node × Node × Node where toFun x := (x.a,x.b,x.right,x.left,x.down,x.up,x.diagonal) invFun p := ⟨p.1,p.2.1,p.2.2.1,p.2.2.2.1,p.2.2.2.2.1,p.2.2.2.2.2.1,p.2.2.2.2.2.2⟩ left_inv := by intro x; cases x; rfl right_inv := by rintro ⟨a,b,right,left,down,up,diagonal⟩; rfl instance : Primcodable EdgeCertificate := Primcodable.ofEquiv _ edgeCode theorem edgeCodeRec : Primrec edgeCode := Primrec.of_equiv theorem edgeARec : Primrec EdgeCertificate.a := (Primrec.fst.comp edgeCodeRec) theorem edgeBRec : Primrec EdgeCertificate.b := (Primrec.fst.comp (Primrec.snd.comp edgeCodeRec)) theorem edgeRightRec : Primrec EdgeCertificate.right := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp edgeCodeRec))) theorem edgeLeftRec : Primrec EdgeCertificate.left := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp edgeCodeRec)))) theorem edgeDownRec : Primrec EdgeCertificate.down := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp edgeCodeRec))))) theorem edgeUpRec : Primrec EdgeCertificate.up := (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp edgeCodeRec)))))) theorem edgeDiagonalRec : Primrec EdgeCertificate.diagonal := (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp edgeCodeRec)))))) theorem mkEdgeRec {x0 : X → Node} {x1 : X → Node} {x2 : X → Node} {x3 : X → Node} {x4 : X → Node} {x5 : X → Node} {x6 : X → Node} (h0 : Primrec x0) (h1 : Primrec x1) (h2 : Primrec x2) (h3 : Primrec x3) (h4 : Primrec x4) (h5 : Primrec x5) (h6 : Primrec x6) : Primrec (fun u => EdgeCertificate.mk (x0 u) (x1 u) (x2 u) (x3 u) (x4 u) (x5 u) (x6 u)) := (Primrec.of_equiv_symm (e:=edgeCode)).comp (h0.pair (h1.pair (h2.pair (h3.pair (h4.pair (h5.pair h6)))))) theorem poolRec {w : X → List Nat} {ts : X → List (List Bool)} (hw : Primrec w) (ht : Primrec ts) : Primrec (fun x => P455CatalogueBounds.pool (w x) (ts x)) := by apply Primrec.list_flatMap hw apply Primrec₂.mk apply Primrec.list_flatMap (hw.comp Primrec.fst) apply Primrec₂.mk apply Primrec.list_map (ht.comp (Primrec.fst.comp Primrec.fst)) exact (mkNodeRec (Primrec.snd.comp (Primrec.fst.comp Primrec.fst)) (Primrec.snd.comp Primrec.fst) Primrec.snd).to₂ end P455WriterEdge end /- Begin Problem455WriterTileRec (from finite-semigroup-identity-bases). -/ section namespace P455WriterTiles open P455PaddedTiles variable {A : Type} [Primcodable A] theorem replicateRec {B : Type} [Primcodable B] {n : A → Nat} {v : A → B} (hn : Primrec n) (hv : Primrec v) : Primrec fun a => List.replicate (n a) (v a) := (Primrec.list_map (Primrec.list_range.comp hn) (hv.comp Primrec.fst).to₂).of_eq (fun a => by simp [List.map_const']) theorem tokenRec {n k : A → Nat} (hn : Primrec n) (hk : Primrec k) : Primrec fun a => tokenN (n a) (k a) := Primrec.list_append.comp (replicateRec hk (.const true)) (replicateRec (Primrec.nat_sub.comp (Primrec.succ.comp hn) hk) (.const false)) theorem rawCodeRec : Primrec₂ rawCode := by let A := Nat × TileData have n : Primrec fun a : A => a.1 := Primrec.fst have t := Primrec.snd (α := Nat) (β := TileData) have t1 := Primrec.snd.comp t have t2 := Primrec.snd.comp t1 have t3 := Primrec.snd.comp t2 have t4 := Primrec.snd.comp t3 have t5 := Primrec.snd.comp t4 have t6 := Primrec.snd.comp t5 have t7 := Primrec.snd.comp t6 have t8 := Primrec.snd.comp t7 apply Primrec₂.mk apply Primrec.list_cons.comp (Primrec.fst.comp t) apply Primrec.list_cons.comp (Primrec.fst.comp t1) apply Primrec.list_cons.comp (Primrec.fst.comp t2) apply Primrec.list_cons.comp (Primrec.fst.comp t3) apply Primrec.list_cons.comp (Primrec.fst.comp t4) apply Primrec.list_cons.comp (Primrec.fst.comp t5) exact Primrec.list_append.comp (tokenRec n (Primrec.fst.comp t6)) (Primrec.list_append.comp (tokenRec n (Primrec.succ.comp (Primrec.fst.comp t7))) (Primrec.list_append.comp (tokenRec n (Primrec.fst.comp t8)) (tokenRec n (Primrec.succ.comp (Primrec.snd.comp t8))))) theorem impliesRec {p q : A → Prop} [DecidablePred p] [DecidablePred q] (hp : PrimrecPred p) (hq : PrimrecPred q) : PrimrecPred fun a => p a → q a := by apply (PrimrecPred.or (PrimrecPred.not hp) hq).of_eq intro a simp [imp_iff_not_or] theorem eligibleRec : Primrec₂ (fun d t => decide (eligible d t)) := by let A := MachineData × TileData have d := Primrec.fst (α := MachineData) (β := TileData) have v := Primrec.snd.comp d have v2 := Primrec.snd.comp v have v3 := Primrec.snd.comp v2 have v4 := Primrec.snd.comp v3 have n := Primrec.fst.comp d have t := Primrec.snd (α := MachineData) (β := TileData) have t1 := Primrec.snd.comp t have t2 := Primrec.snd.comp t1 have t3 := Primrec.snd.comp t2 have t4 := Primrec.snd.comp t3 have t5 := Primrec.snd.comp t4 have t6 := Primrec.snd.comp t5 have t7 := Primrec.snd.comp t6 have t8 := Primrec.snd.comp t7 have leftFlag := Primrec.fst.comp t have rightFlag := Primrec.fst.comp t1 have top := Primrec.fst.comp t2 have bottom := Primrec.fst.comp t3 have row := Primrec.fst.comp t4 have col := Primrec.fst.comp t5 have l := Primrec.fst.comp t6 have c := Primrec.fst.comp t7 have r := Primrec.fst.comp t8 have b := Primrec.snd.comp t8 let L (x : A) := x.2.1 = true have hl : PrimrecPred L := Primrec.eq.comp leftFlag (.const true) have init := Primrec.ite hl (Primrec.fst.comp v3) (Primrec.fst.comp v2) have ix := Primrec.nat_add.comp (Primrec.nat_mul.comp (Primrec.nat_add.comp (Primrec.nat_mul.comp l n) c) (Primrec.succ.comp n)) r have next := Primrec.option_getD.comp (Primrec.list_getElem?.comp (Primrec.snd.comp v4) ix) (.const none) have mark := Primrec.option_getD.comp (Primrec.list_getElem?.comp (Primrec.fst.comp v) c) (.const false) apply Primrec₂.mk unfold eligible exact (PrimrecPred.and (Primrec.eq.comp next (Primrec.option_some.comp b)) <| PrimrecPred.and (Primrec.eq.comp leftFlag (Primrec.eq.comp l (.const 0)).decide) <| PrimrecPred.and (Primrec.eq.comp rightFlag (Primrec.eq.comp r (.const 0)).decide) <| PrimrecPred.and (Primrec.eq.comp mark leftFlag) <| PrimrecPred.and (impliesRec hl (Primrec.eq.comp col (.const false))) <| PrimrecPred.and (impliesRec (Primrec.eq.comp top (.const true)) (PrimrecPred.and (Primrec.eq.comp row (.const false)) (Primrec.eq.comp c init))) (impliesRec (Primrec.eq.comp bottom (.const true)) (impliesRec hl (Primrec.eq.comp c (Primrec.fst.comp v4))))).decide theorem tagsRec : Primrec tags := Primrec.list_map (P455GraphPrim.filter (poolRec.comp Primrec.fst) eligibleRec) (rawCodeRec.comp (Primrec.fst.comp Primrec.fst) Primrec.snd).to₂ end P455WriterTiles end /- Begin Problem455WriterLocal (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram open P455EffectiveMachine P455MachineLocal P455MachineCleanup P455MachineTable P455PaddedTiles def act (m : Raw) (v : Nat) : Option Triple := if 0 some sym | some i,none,none => some (send ng sym 2 i) | none,none,some i => some (send ng sym 0 i) | none,some i,none => if (i.2.2=0 ∧ left=true) ∨ (i.2.2=2 ∧ right=true) then none else some (send ng i.2.1 1 i) | _,_,_ => none def localValue (m : Raw) (l : Option Nat) (c : Nat) (r : Option Nat) := output (g m) (c%(g m)) l.isNone r.isNone (l.bind (act m)) (act m c) (r.bind (act m)) theorem act_spec (M : Ordinary ng nq) (v : Fin (ng*((nq+2)+1))) : act (data M) v.val=(action (normalized M).delta (dec (normalized M) v)).map numIns := by unfold act action dec by_cases h : 0 rfl | some c => exact act_spec M c theorem send_spec (a : Fin ng) (i : Ins (Fin ng) (Fin ns)) (d : Direction) : send ng a.val (dirCode d) (numIns i)=(enc ⟨a,sends i d⟩).val := by obtain ⟨z,b,e⟩:=i cases e <;> cases d <;> simp [send,numIns,sends,enc,headIndex,dirCode] theorem output_spec (delta : Fin ns → Fin ng → Ins (Fin ng) (Fin ns)) (l : Option (C ng ns)) (c : C ng ns) (r : Option (C ng ns)) : output ng c.sym.val l.isNone r.isNone ((l.bind (action delta)).map numIns) ((action delta c).map numIns) ((r.bind (action delta)).map numIns) = ((update delta l c r).map enc).map Fin.val := by unfold update cases e₁ : l.bind (action delta) with | none => cases e₂ : action delta c with | none => cases e₃ : r.bind (action delta) with | none => simp [output,enc,headIndex] | some i => exact congrArg some (send_spec c.sym i .left) | some i => cases e₃ : r.bind (action delta) with | some j => rfl | none => have dl : (numIns i).2.2=0 ↔ i.dir=.left := by cases h : i.dir <;> simp [numIns,h,dirCode] have dr : (numIns i).2.2=2 ↔ i.dir=.right := by cases h : i.dir <;> simp [numIns,h,dirCode] change (if ((numIns i).2.2=0 ∧ l.isNone=true) ∨ ((numIns i).2.2=2 ∧ r.isNone=true) then none else some (send ng i.symbol.val 1 (numIns i))) = _ by_cases e : (i.dir=.left ∧ l.isNone=true) ∨ (i.dir=.right ∧ r.isNone=true) · simp only [dl,dr,e,if_true]; rfl · simp only [dl,dr,e,if_false] exact congrArg some (send_spec i.symbol i .stay) | some i => cases e₂ : action delta c with | some j => cases r.bind (action delta) <;> rfl | none => cases e₃ : r.bind (action delta) with | none => exact congrArg some (send_spec c.sym i .right) | some j => rfl theorem localValue_spec (M : Ordinary ng nq) (l : Option (Fin (ng*((nq+2)+1)))) (c : Fin (ng*((nq+2)+1))) (r : Option (Fin (ng*((nq+2)+1)))) : localValue (data M) (l.map Fin.val) c.val (r.map Fin.val) = ((compile (normalized M)).next l c r).map Fin.val := by unfold localValue rw [opt_act,opt_act,act_spec] have em {A B : Type} (f : A → B) (o : Option A) : (o.map f).isNone=o.isNone := by cases o <;> rfl simpa only [em, data, g, dec, compile] using (output_spec (normalized M).delta (l.map (dec (normalized M))) (dec (normalized M) c) (r.map (dec (normalized M)))) end P455WriterProgram end /- Begin Problem455PackedOutput (from finite-semigroup-identity-bases). -/ section /- Connect the numeric product and raw class tables to the relaxed writer premise: this output may have an entirely different element numbering. -/ namespace P455PackedOutput open P455Table P455TableBits P455NumericProduct P455TableSemantics P455EffectiveMachine open P455MachineCleanup P455MachineTable P455EffectiveWriter P455MachineParse open P455EffectiveChain P455AnyPresentation def alternative (M : Ordinary g q) := P455Packed.serialize (P455Packed.prepared (compile (normalized M))) theorem alternative_represents (M : Ordinary g q) : Represents (alternative M) (P455MachineReduction.model M) := P455Packed.serialize_represents (compile (normalized M)) def selfTable (input : List Bool) : Matrix := match blankSource input with | none => [[0]] | some ⟨_,_,M⟩ => alternative M def selfOutput (input : List Bool) := encode (selfTable input) theorem on_self (M : Ordinary g q) (B : Alphabet M) : selfTable (selfBits M B)=alternative (diagonalInput M B).2 := by simp [selfTable,blankSource_self] theorem pure_basis_on_self (M : Ordinary g q) (B : Alphabet M) : P455PureSemigroup.Basis (selfTable (selfBits M B)) ↔ ¬SelfHalt M B := by rw [on_self] obtain ⟨X,table,⟨p⟩⟩ := alternative_represents (diagonalInput M B).2 rw [table] exact (P455PureSemigroup.basis_iff (output_laws p).1).trans ((P455TableSemantics.basis_iff p).trans (diagonal_basis M B)) theorem delivers_presentation (W : Ordinary g q) (A O : Alphabet W) (realizes : ∀ x, Delivers W A x W O (selfOutput x)) : WritesPresentation W A O := by intro k s P B obtain ⟨X,table,yes⟩ := alternative_represents (diagonalInput P B).2 refine ⟨X,yes,?_⟩ simpa only [selfOutput,on_self,table] using realizes (selfBits P B) theorem no_decider_if_realized (W : Ordinary g q) (A O : Alphabet W) (realizes : ∀ x, Delivers W A x W O (selfOutput x)) : ¬ P455Operational.TableDeciderExists := by rintro ⟨_,_,D,B,ans,reads⟩ exact no_table_decider W A O (delivers_presentation W A O realizes) D B ans reads end P455PackedOutput end /- Begin Problem455WriterEdgeSearch (from finite-semigroup-identity-bases). -/ section namespace P455WriterEdge open P455Witness variable {X : Type} [Primcodable X] theorem certificatesRec {w : X → List Nat} {ts : X → List (List Bool)} (hw : Primrec w) (ht : Primrec ts) : Primrec (fun x => P455Enum.certificates (w x) (ts x)) := by have ns := poolRec hw ht apply Primrec.list_flatMap ns apply Primrec₂.mk apply Primrec.list_flatMap (ns.comp Primrec.fst) apply Primrec₂.mk apply Primrec.list_flatMap ((ns.comp Primrec.fst).comp Primrec.fst) apply Primrec₂.mk apply Primrec.list_flatMap (((ns.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) apply Primrec₂.mk apply Primrec.list_flatMap ((((ns.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) apply Primrec₂.mk apply Primrec.list_flatMap (((((ns.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) apply Primrec₂.mk apply Primrec.list_map ((((((ns.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) apply Primrec₂.mk exact mkEdgeRec ((((((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) (((((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) ((((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) (((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) ((Primrec.snd.comp Primrec.fst).comp Primrec.fst) (Primrec.snd.comp Primrec.fst) Primrec.snd theorem functionalitiesRec {w : X → List Nat} {ts : X → List (List Bool)} (hw : Primrec w) (ht : Primrec ts) : Primrec (fun x => P455Enum.functionalities (w x) (ts x)) := by have ns := poolRec hw ht apply Primrec.list_flatMap ns apply Primrec₂.mk apply Primrec.list_flatMap (Primrec.const [false,true]) apply Primrec₂.mk apply Primrec.list_flatMap ((ns.comp Primrec.fst).comp Primrec.fst) apply Primrec₂.mk apply Primrec.list_flatMap (((ns.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) apply Primrec₂.mk apply Primrec.list_flatMap (Primrec.const P455Enum.directions.list) apply Primrec₂.mk apply Primrec.list_map (Primrec.const [false,true]) apply Primrec₂.mk exact mkFuncRec (((((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) ((((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) (((Primrec.snd.comp Primrec.fst).comp Primrec.fst).comp Primrec.fst) ((Primrec.snd.comp Primrec.fst).comp Primrec.fst) (Primrec.snd.comp Primrec.fst) Primrec.snd end P455WriterEdge end /- Begin Problem455WriterProfiles (from finite-semigroup-identity-bases). -/ section namespace P455WriterProfiles open Problem455.Slots P455WriterTiles P455BinaryEquality abbrev W := List Nat abbrev Tags := List (List Bool) abbrev Candidate := Nat × Nat × List Bool × Bool variable {A : Type} [Primcodable A] theorem pairRec {a b : A → Nat} {v : A → Bool} (ha : Primrec a) (hb : Primrec b) (hv : Primrec v) : Primrec fun x => pair (a x) (b x) (v x) := by let cons := @Primrec.list_cons Nat _ exact Primrec.ite (Primrec.eq.comp hv (.const true)) (cons.comp hb (cons.comp ha (.const []))) (cons.comp ha (cons.comp hb (.const []))) theorem profileRec {a b : A → Nat} {t : A → List Bool} {v : A → Bool} (ha : Primrec a) (hb : Primrec b) (ht : Primrec t) (hv : Primrec v) : Primrec fun x => profile (a x) (b x) (t x) (v x) := by let cons := @Primrec.list_cons Nat _ have ab := cons.comp ha (cons.comp hb (.const [])) have fixed := cons.comp ha (cons.comp ha (cons.comp hb (cons.comp ha (cons.comp hb (cons.comp hb (.const [])))))) have reps := Primrec.list_flatten.comp (replicateRec (.const 5) (cons.comp ha (cons.comp hb ab))) have mid : Primrec (fun x => (t x).flatMap (pair (a x) (b x))) := Primrec.list_flatMap ht (Primrec₂.mk (pairRec (A := A × Bool) (ha.comp Primrec.fst) (hb.comp Primrec.fst) Primrec.snd)) exact Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp (Primrec.list_append.comp fixed reps) mid) ab) (Primrec.list_append.comp (pairRec ha hb hv) ab) def candidates (w : W) (ts : Tags) : List Candidate := choices w (choices w (choices ts [false,true])) def test (r : Nat) (w : W) (c : Candidate) := decide (c.1 ≠ c.2.1 ∧ c.2.2.1.length+16=r ∧ w=profile c.1 c.2.1 c.2.2.1 c.2.2.2) def isProfile (r : Nat) (ts : Tags) (w : W) := (candidates w ts).any (test r w) theorem correct {n} (M : P455PaddedTiles.MachineTable n) (r w) : isProfile r (P455Enum.tags M) w=true ↔ IsProfile r (P455PaddedTiles.allowed M) w := by simp only [isProfile,candidates,choices,List.any_eq_true,List.mem_flatMap,List.mem_map,test,decide_eq_true_eq] constructor · rintro ⟨_,⟨a,_,_,⟨b,_,_,⟨t,ht,bit,_,rfl⟩,rfl⟩,rfl⟩,hne,hlen,hw⟩ exact ⟨a,b,t,bit,hne,hlen,P455Enum.mem_tags.mp ht,hw⟩ · rintro ⟨a,b,t,bit,hne,hlen,ht,hw⟩ have names : a∈w ∧ b∈w := by rw [hw]; exact P455Enum.profile_names refine ⟨(a,b,t,bit),⟨a,names.1,_,⟨b,names.2,_,⟨t,P455Enum.mem_tags.mpr ht,bit,?_,rfl⟩,rfl⟩,rfl⟩,hne,hlen,hw⟩ cases bit <;> simp theorem isProfileRec {r : A → Nat} {ts : A → Tags} {w : A → W} (hr : Primrec r) (ht : Primrec ts) (hw : Primrec w) : Primrec fun a => isProfile (r a) (ts a) (w a) := by apply P455GraphPrim.anyB (choicesRec hw (choicesRec hw (choicesRec ht (.const [false,true])))) apply Primrec₂.mk have p := Primrec.snd (α := A) (β := Candidate) have x := Primrec.fst.comp p have y := Primrec.fst.comp (Primrec.snd.comp p) have suffix := Primrec.snd.comp (Primrec.snd.comp p) have t := Primrec.fst.comp suffix have b := Primrec.snd.comp suffix exact (PrimrecPred.and (PrimrecPred.not (Primrec.eq.comp x y)) <| PrimrecPred.and (Primrec.eq.comp (Primrec.nat_add.comp (Primrec.list_length.comp t) (.const 16)) (hr.comp Primrec.fst)) (Primrec.eq.comp (hw.comp Primrec.fst) (profileRec x y t b))).decide end P455WriterProfiles end /- Begin Problem455WriterAdjacency (from finite-semigroup-identity-bases). -/ section namespace P455WriterTiles open P455PaddedTiles namespace RawTile def left (p : TileData) := p.1 def right (p : TileData) := p.2.1 def top (p : TileData) := p.2.2.1 def bottom (p : TileData) := p.2.2.2.1 def oddRow (p : TileData) := p.2.2.2.2.1 def oddColumn (p : TileData) := p.2.2.2.2.2.1 def l (p : TileData) := p.2.2.2.2.2.2.1 def c (p : TileData) := p.2.2.2.2.2.2.2.1 def r (p : TileData) := p.2.2.2.2.2.2.2.2.1 def b (p : TileData) := p.2.2.2.2.2.2.2.2.2 theorem leftRec : Primrec left := Primrec.fst theorem rightRec : Primrec right := (Primrec.fst).comp Primrec.snd theorem topRec : Primrec top := ((Primrec.fst).comp Primrec.snd).comp Primrec.snd theorem bottomRec : Primrec bottom := (((Primrec.fst).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd theorem oddRowRec : Primrec oddRow := ((((Primrec.fst).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd theorem oddColumnRec : Primrec oddColumn := (((((Primrec.fst).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd theorem lRec : Primrec l := ((((((Primrec.fst).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd theorem cRec : Primrec c := (((((((Primrec.fst).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd theorem rRec : Primrec r := ((((((((Primrec.fst).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd theorem bRec : Primrec b := ((((((((Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd).comp Primrec.snd end RawTile def across (p q : TileData) : Prop := RawTile.right p=false ∧ RawTile.left q=false ∧ RawTile.top p=RawTile.top q ∧ RawTile.bottom p=RawTile.bottom q ∧ RawTile.oddRow p=RawTile.oddRow q ∧ RawTile.oddColumn p≠RawTile.oddColumn q ∧ RawTile.l q=RawTile.c p+1 ∧ RawTile.r p=RawTile.c q+1 def down (p q : TileData) : Prop := RawTile.bottom p=false ∧ RawTile.top q=false ∧ RawTile.left p=RawTile.left q ∧ RawTile.right p=RawTile.right q ∧ RawTile.oddColumn p=RawTile.oddColumn q ∧ RawTile.oddRow p≠RawTile.oddRow q ∧ RawTile.b p=RawTile.c q instance acrossDec (p q : TileData) : Decidable (across p q) := by unfold across; infer_instance instance downDec (p q : TileData) : Decidable (down p q) := by unfold down; infer_instance private theorem asSome (u : Option (Fin n)) (v : Fin n) : letter u = v.val+1 ↔ u=some v := by cases u <;> simp [letter,Fin.ext_iff] theorem across_correct (p q : Tile n) : across (raw p) (raw q) ↔ Horizontal p q := by simp only [across,Horizontal,raw,RawTile.right,RawTile.left,RawTile.top,RawTile.bottom,RawTile.oddRow, RawTile.oddColumn,RawTile.l,RawTile.c,RawTile.r,asSome] theorem down_correct (p q : Tile n) : down (raw p) (raw q) ↔ Vertical p q := by simp only [down,Vertical,raw,RawTile.left,RawTile.right,RawTile.top,RawTile.bottom,RawTile.oddRow, RawTile.oddColumn,RawTile.b,RawTile.c,Fin.ext_iff] def pairTest (R : TileData → TileData → Bool) (n : Nat) (s t : List Bool) := (pool n).any fun p => (pool n).any fun q => decide (rawCode n p=s) && decide (rawCode n q=t) && R p q theorem pairTest_correct (R : TileData → TileData → Bool) (X : Tile n → Tile n → Prop) (correct : ∀ p q, R (raw p) (raw q)=true ↔ X p q) (s t) : pairTest R n s t = true ↔ ∃ p q, code p=s ∧ code q=t ∧ X p q := by simp only [pairTest,←map_raw,List.any_eq_true,List.mem_map,Bool.and_eq_true,decide_eq_true_eq] constructor · rintro ⟨_,⟨p,_,rfl⟩,_,⟨q,_,rfl⟩,⟨ps,qt⟩,h⟩ exact ⟨p,q,ps,qt,(correct p q).mp h⟩ · rintro ⟨p,q,ps,qt,h⟩ exact ⟨_,⟨p,(P455Enum.tiles n).mem p,rfl⟩,_,⟨q,(P455Enum.tiles n).mem q,rfl⟩,⟨ps,qt⟩,(correct p q).mpr h⟩ def horizontal (n : Nat) (s t : List Bool) := pairTest (fun p q => decide (across p q)) n s t def vertical (n : Nat) (s t : List Bool) := pairTest (fun p q => decide (down p q)) n s t theorem horizontal_correct (n s t) : horizontal n s t=true ↔ (system n).horizontal s t := pairTest_correct _ _ (fun p q=>by simpa using across_correct p q) s t theorem vertical_correct (n s t) : vertical n s t=true ↔ (system n).vertical s t := pairTest_correct _ _ (fun p q=>by simpa using down_correct p q) s t open RawTile in theorem acrossRec : Primrec₂ (fun p q => decide (across p q)) := by exact (PrimrecPred.and (Primrec.eq.comp (rightRec.comp Primrec.fst) (.const false)) <| PrimrecPred.and (Primrec.eq.comp (leftRec.comp Primrec.snd) (.const false)) <| PrimrecPred.and (Primrec.eq.comp (topRec.comp Primrec.fst) (topRec.comp Primrec.snd)) <| PrimrecPred.and (Primrec.eq.comp (bottomRec.comp Primrec.fst) (bottomRec.comp Primrec.snd)) <| PrimrecPred.and (Primrec.eq.comp (oddRowRec.comp Primrec.fst) (oddRowRec.comp Primrec.snd)) <| PrimrecPred.and (PrimrecPred.not (Primrec.eq.comp (oddColumnRec.comp Primrec.fst) (oddColumnRec.comp Primrec.snd))) <| PrimrecPred.and (Primrec.eq.comp (lRec.comp Primrec.snd) (Primrec.succ.comp (cRec.comp Primrec.fst))) (Primrec.eq.comp (rRec.comp Primrec.fst) (Primrec.succ.comp (cRec.comp Primrec.snd)))).decide.to₂ open RawTile in theorem downRec : Primrec₂ (fun p q => decide (down p q)) := by exact (PrimrecPred.and (Primrec.eq.comp (bottomRec.comp Primrec.fst) (.const false)) <| PrimrecPred.and (Primrec.eq.comp (topRec.comp Primrec.snd) (.const false)) <| PrimrecPred.and (Primrec.eq.comp (leftRec.comp Primrec.fst) (leftRec.comp Primrec.snd)) <| PrimrecPred.and (Primrec.eq.comp (rightRec.comp Primrec.fst) (rightRec.comp Primrec.snd)) <| PrimrecPred.and (Primrec.eq.comp (oddColumnRec.comp Primrec.fst) (oddColumnRec.comp Primrec.snd)) <| PrimrecPred.and (PrimrecPred.not (Primrec.eq.comp (oddRowRec.comp Primrec.fst) (oddRowRec.comp Primrec.snd))) <| Primrec.eq.comp (bRec.comp Primrec.fst) (cRec.comp Primrec.snd)).decide.to₂ theorem pairTestRec {A : Type} [Primcodable A] {R : TileData → TileData → Bool} (rel : Primrec₂ R) {n : A → Nat} {s t : A → List Bool} (hn : Primrec n) (hs : Primrec s) (ht : Primrec t) : Primrec fun a => pairTest R (n a) (s a) (t a) := by apply P455GraphPrim.anyB (poolRec.comp hn) apply Primrec₂.mk apply P455GraphPrim.anyB (poolRec.comp (hn.comp Primrec.fst)) apply Primrec₂.mk have g := Primrec.fst (α := A) (β := TileData) |>.comp (Primrec.fst (β := TileData)) have p : Primrec fun a : (A×TileData)×TileData => a.1.2 := Primrec.snd.comp Primrec.fst have q : Primrec fun a : (A×TileData)×TileData => a.2 := Primrec.snd exact Primrec.and.comp (Primrec.and.comp (Primrec.eq.comp (rawCodeRec.comp (hn.comp g) p) (hs.comp g)).decide (Primrec.eq.comp (rawCodeRec.comp (hn.comp g) q) (ht.comp g)).decide) (rel.comp p q) theorem horizontalRec {A : Type} [Primcodable A] {n : A → Nat} {s t : A → List Bool} (hn : Primrec n) (hs : Primrec s) (ht : Primrec t) : Primrec fun a => horizontal (n a) (s a) (t a) := pairTestRec acrossRec hn hs ht theorem verticalRec {A : Type} [Primcodable A] {n : A → Nat} {s t : A → List Bool} (hn : Primrec n) (hs : Primrec s) (ht : Primrec t) : Primrec fun a => vertical (n a) (s a) (t a) := pairTestRec downRec hn hs ht end P455WriterTiles end /- Begin Problem455WriterMachineData (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram open P455EffectiveMachine P455MachineLocal P455MachineCleanup P455MachineTable P455PaddedTiles P455EffectiveWriter def dimension (m : Raw) := g m*((q m+2)+1) def neighbour (i : Nat) : Option Nat := if i=0 then none else some (i-1) def line (m : Raw) (n l c : Nat) := (List.range (n+1)).map fun r => localValue m (neighbour l) c (neighbour r) def slab (m : Raw) (n l : Nat) := (List.range n).flatMap (line m n l) def grid (m : Raw) (n : Nat) := (List.range (n+1)).flatMap (slab m n) def machineData (m : Raw) : P455WriterTiles.MachineData := let n := dimension m (n,(List.range n).map (fun c => decide (c%(g m)=marker m)),blank m,g m*(start m+1)+marker m, g m*((q m+1)+1)+marker m,grid m n) theorem get_slab (m : Raw) (n : Nat) (l : Nat) : (slab m n l).length=n*(n+1) := by simp [slab,line,List.length_flatMap,Function.comp_def,List.map_const'] theorem get_grid (m : Raw) (l c r : Nat) (hl : l < dimension m + 1) (hc : c < dimension m) (hr : r < dimension m+1) : (grid m (dimension m))[P455WriterTiles.address (dimension m) l c r]? = some (localValue m (neighbour l) c (neighbour r)) := by let n := dimension m change (grid m n)[(l*n+c)*(n+1)+r]?=_ rw [show (l*n+c)*(n+1)+r=l*(n*(n+1))+(c*(n+1)+r) by rw [Nat.add_mul,Nat.mul_assoc,Nat.add_assoc]] have D : c*(n+1)+r simp [letter] | some a => simp [letter] theorem neighbour_letter (x : Option (Fin n)) : neighbour (letter x)=x.map Fin.val := by cases x <;> simp [letter,neighbour] theorem machineData_models (M : Ordinary ng nq) : P455WriterTiles.Models (machineData (data M)) (compile (normalized M)) := by constructor · rfl · intro c simp only [P455WriterTiles.marker,machineData,List.getElem?_map] rw [List.getElem?_eq_getElem (by simpa only [List.length_range] using (show c.val < dimension (data M) from c.isLt)),List.getElem_range] change decide (c.val%ng=M.marker.val)=decide ((dec (normalized M) c).sym=M.marker) simp only [Fin.ext_iff]; rfl · intro b; cases b <;> simp [machineData,P455WriterTiles.initial,data,g,start,marker,blank,compile,enc,headIndex,normalized,old] · rfl · intro l c r change (grid (data M) (dimension (data M)))[P455WriterTiles.address (dimension (data M)) (letter l) c.val (letter r)]?.getD none=_ rw [get_grid _ _ _ _ (letter_lt l) c.isLt (letter_lt r),neighbour_letter,neighbour_letter] exact localValue_spec M l c r def fromBits (w : List Bool) := machineData (blankRaw w) theorem fromBits_self (M : Ordinary ng nq) (A : Alphabet M) : P455WriterTiles.Models (fromBits (selfBits M A)) (compile (normalized (diagonalInput M A).2)) := by unfold fromBits; rw [blank_self]; exact machineData_models _ end P455WriterProgram end /- Begin Problem455TableDecision (from finite-semigroup-identity-bases). -/ section namespace P455TableDecision open P455Table P455TableBits P455TableSemantics P455MachineCleanup P455EffectiveMachine open P455EffectiveChain P455AnyPresentation P455Operational def PureDecides (D : Ordinary g q) (B : Alphabet D) (ans : Fin q → Bool) := ∀ T : Matrix, SemigroupTable T → ∃ b, Answers D B ans (encode T) b ∧ (b=true ↔ P455PureSemigroup.Basis T) def PureDeciderExists := ∃ (g q : Nat) (D : Ordinary g q) (B : Alphabet D) (ans : Fin q → Bool), PureDecides D B ans def PresentationWriterExists := ∃ (g q : Nat) (W : Ordinary g q) (A O : Alphabet W), WritesPresentation W A O theorem decider_iff (D : Ordinary g q) (B : Alphabet D) (ans : Fin q → Bool) : PureDecides D B ans ↔ DecidesTable D B ans := by constructor <;> intro h T valid <;> obtain ⟨b,read,ok⟩ := h T valid · exact ⟨b,read,ok.trans (P455PureSemigroup.basis_iff valid)⟩ · exact ⟨b,read,ok.trans (P455PureSemigroup.basis_iff valid).symm⟩ /-- Conditional only on the existence of one finite physical writer, with any correct numbering of its output monoid. -/ theorem no_table_algorithm_of_presentation_writer : PresentationWriterExists → ¬PureDeciderExists := by rintro ⟨_,_,W,A,O,writes⟩ ⟨_,_,D,B,ans,pure⟩ exact no_table_decider W A O writes D B ans ((decider_iff D B ans).mp pure) /-- The unconditional bit-string reduction including validity of the finite output and its ordinary binary basis predicate, for every raw input. -/ theorem encoded_reduction (s : List Bool) : parse (P455RawReduction.blankBits s)=some (P455RawReduction.blankTable s) ∧ SemigroupTable (P455RawReduction.blankTable s) ∧ HasUnit (P455RawReduction.blankTable s) ∧ (P455PureSemigroup.Basis (P455RawReduction.blankTable s) ↔ ¬P455RawReduction.realizesHalt (P455RawReduction.parseBlank s)) := by obtain ⟨parse,sem,unit,_⟩ := P455RawReduction.exact_blank s exact ⟨parse,sem,unit,P455PureSemigroup.raw_basis s⟩ end P455TableDecision end /- Begin Problem455PayloadBridge (from finite-semigroup-identity-bases). -/ section /- The first-order catalogue input to the actual bit writer. -/ namespace P455PayloadBridge open P455PaddedTiles P455MachineCleanup P455MachineTable P455MachineParse def selfPayload (s : List Bool) : Option P455SerializePrim.Data := match blankSource s with | none => none | some ⟨_, _, M⟩ => some (P455SerializePrim.ofPayload (P455Packed.prepared (compile (normalized M)))) theorem primitive_field {n : Nat} (M : MachineTable n) : (P455Packed.prepared M).primitive = P455CataloguePrim.primitive (widthCode n + 16) := by simp only [P455Packed.prepared, P455Packed.names, P455Encoded.indices, P455Encoded.useCover, P455CataloguePrim.primitive] apply List.map_congr_left intro i _ rfl theorem selfOutput_computable (h : Computable selfPayload) : Computable P455PackedOutput.selfOutput := by let fallback := P455TableBits.encode [[0]] let serialize := fun d : P455SerializePrim.Data => P455TableBits.encode (P455Packed.serialize (P455SerializePrim.asPayload d)) have certified : Computable₂ (fun (_ : List Bool) d => serialize d) := (P455SerializePrim.bits.to_comp.comp Computable.snd).to₂ apply (Computable.option_casesOn h (Computable.const fallback) certified).of_eq intro s unfold selfPayload P455PackedOutput.selfOutput P455PackedOutput.selfTable cases blankSource s with | none => rfl | some source => rcases source with ⟨g, q, M⟩ simp only [serialize, P455SerializePrim.as_of, P455PackedOutput.alternative] end P455PayloadBridge end /- Begin Problem455WriterSlotTypes (from finite-semigroup-identity-bases). -/ section namespace P455WriterSlots open P455Witness open P455WriterTiles (choicesRec map_choices choices) variable {A : Type} [Primcodable A] abbrev ContactData := (Tag × Bool) ⊕ (Fin 5 × Bool) def contactCode : ContactChoice ≃ ContactData where toFun | .record t b => .inl (t,b) | .port p b => .inr (p,b) invFun | .inl (t,b) => .record t b | .inr (p,b) => .port p b left_inv a := by cases a <;> rfl right_inv a := by rcases a with ⟨_,_⟩|⟨_,_⟩ <;> rfl instance : Primcodable ContactChoice := Primcodable.ofEquiv _ contactCode theorem contactCodeRec : Primrec contactCode := Primrec.of_equiv def defectCode : SlotDefect ≃ Nat ⊕ W where toFun | .deficient a => .inl a | .overflow xs => .inr xs invFun | .inl a => .deficient a | .inr xs => .overflow xs left_inv a := by cases a <;> rfl right_inv a := by cases a <;> rfl instance : Primcodable SlotDefect := Primcodable.ofEquiv _ defectCode theorem defectCodeRec : Primrec defectCode := Primrec.of_equiv abbrev SlotData := Node × Bool × Bool × List (Nat × ContactChoice) × Nat × SlotDefect def slotCode : SlotCertificate ≃ SlotData where toFun s := (s.anchor,s.bit,s.startAtMate,s.steps,s.terminalIndex,s.defect) invFun | (a,b,m,p,i,d) => ⟨a,b,m,p,i,d⟩ left_inv a := by cases a; rfl right_inv _ := rfl instance : Primcodable SlotCertificate := Primcodable.ofEquiv _ slotCode theorem slotCodeRec : Primrec slotCode := Primrec.of_equiv theorem choicesRec' {ts : A → List Tag} (ht : Primrec ts) : Primrec fun a => P455Enum.choices (ts a) := by let b := [false,true] let f := fun s : Tag × Bool => contactCode.symm (Sum.inl s) let g := fun s : Fin 5 × Bool => contactCode.symm (Sum.inr s) have hf : Primrec f := (Primrec.of_equiv_symm (e:=contactCode)).comp Primrec.sumInl have hg : Primrec g := (Primrec.of_equiv_symm (e:=contactCode)).comp Primrec.sumInr have h1 := Primrec.list_map (choicesRec ht (.const b)) (hf.comp Primrec.snd).to₂ have h2 : Primrec (fun _ : A => (choices (P455Enum.fins 5).list b).map g) := Primrec.const _ apply (Primrec.list_append.comp h1 h2).of_eq intro a simp only [map_choices,P455Enum.choices,b,P455Enum.bools,f,g,contactCode,Equiv.coe_fn_symm_mk] theorem stepsRec {w : A → W} {ts : A → List Tag} (hw : Primrec w) (ht : Primrec ts) : Primrec fun a => P455Enum.steps (w a) (ts a) := choicesRec hw (choicesRec' ht) theorem defectsRec {w : A → W} (hw : Primrec w) : Primrec fun a => P455Enum.defects (w a) := by have f : Primrec SlotDefect.deficient := (Primrec.of_equiv_symm (e:=defectCode)).comp Primrec.sumInl have g : Primrec SlotDefect.overflow := (Primrec.of_equiv_symm (e:=defectCode)).comp Primrec.sumInr exact Primrec.list_append.comp (Primrec.list_map hw (f.comp Primrec.snd).to₂) (Primrec.list_map (P455GraphPrim.wordsUpTo.comp hw (.const 5)) (g.comp Primrec.snd).to₂) theorem slotsRec {w : A → W} {ts : A → List Tag} (hw : Primrec w) (ht : Primrec ts) : Primrec fun a => P455Enum.slots (w a) (ts a) := by let bs := P455Enum.bools.list have h := choicesRec (P455WriterEdge.poolRec hw ht) (choicesRec (.const bs) (choicesRec (.const bs) (choicesRec (P455GraphPrim.wordsUpTo.comp (stepsRec hw ht) (.const 6)) (choicesRec (.const (List.range 12)) (defectsRec hw))))) apply (Primrec.list_map h ((Primrec.of_equiv_symm (e:=slotCode)).comp Primrec.snd).to₂).of_eq intro a simp only [map_choices,P455Enum.slots,bs,choices,List.map_flatMap,List.map_map,Function.comp_def, slotCode,Equiv.coe_fn_symm_mk] end P455WriterSlots end /- Begin Problem455WriterObservations (from finite-semigroup-identity-bases). -/ section namespace P455WriterObservations open Problem455.Slots P455WriterProfiles variable {A X : Type} [Primcodable A] [Primcodable X] theorem selectRec {k w : A → List Nat} (hk : Primrec k) (hw : Primrec w) : Primrec fun a => select (k a) (w a) := P455GraphPrim.filter hw ((P455CataloguePrim.mem'.comp Primrec.snd (hk.comp Primrec.fst)).decide.to₂) def bump (a : Nat) (p : Event) : Event := (p.1, p.2 + if p.1=a then 1 else 0) theorem stamp_add (n f : Nat → Nat) (w : W) : stamp (fun i => n i + f i) w = (stamp n w).map (fun p => (p.1,p.2+f p.1)) := by induction w generalizing n with | nil => rfl | cons a w ih => simp only [stamp,List.map_cons,List.cons.injEq,true_and] have eq : advance (fun i => n i+f i) [a] = fun i => advance n [a] i+f i := by funext i change (n i+f i)+[a].count i=(n i+[a].count i)+f i omega rw [eq,ih] theorem events_cons (a : Nat) (w : W) : events (a::w) = (a,0)::(events w).map (bump a) := by unfold events simp only [stamp,List.cons.injEq,true_and] have eq : advance (fun _ => 0) [a] = fun i : Nat => 0+(if i=a then 1 else 0) := by funext i by_cases h : i=a <;> simp [advance,h,Ne.symm,BEq.comm] rw [eq,stamp_add] rfl theorem eventsRec : Primrec events := by let h (_ : W) (p : Nat × List Event) := (p.1,0)::p.2.map (bump p.1) have hh : Primrec₂ h := by apply Primrec₂.mk apply Primrec.list_cons.comp (Primrec.pair (Primrec.fst.comp Primrec.snd) (.const 0)) apply Primrec.list_map (Primrec.snd.comp Primrec.snd) apply Primrec₂.mk have letter := Primrec.fst.comp (Primrec.snd (α := (W×(Nat×List Event))) (β := Event)) exact Primrec.pair letter (Primrec.nat_add.comp (Primrec.snd.comp Primrec.snd) (Primrec.ite (Primrec.eq.comp letter (Primrec.fst.comp (Primrec.snd.comp Primrec.fst))) (.const 1) (.const 0))) apply (Primrec.list_foldr (h:=h) (Primrec.id (α:=W)) (Primrec.const ([] : List Event)) hh).of_eq intro w induction w with | nil => rfl | cons a w ih => rw [events_cons] exact congrArg (fun tail => (a,0)::tail.map (bump a)) ih def subsequences (l : List X) := l.foldr (fun x s => s ++ s.map (List.cons x)) [[]] theorem mem_subsequences {α : Type} (s t : List α) : s∈subsequences t ↔ s.Sublist t := by induction t generalizing s with | nil => simp [subsequences] | cons a l ih => change s∈subsequences l ++ (subsequences l).map (List.cons a) ↔ _ simp only [List.mem_append,List.mem_map,ih,List.sublist_cons_iff] tauto theorem subsequencesRec : Primrec (@subsequences X) := by let h (_ : List X) (p : X×List (List X)) := p.2 ++ p.2.map (List.cons p.1) apply Primrec.list_foldr (h:=h) (Primrec.id (α:=List X)) (Primrec.const [[]]) apply Primrec₂.mk exact Primrec.list_append.comp (Primrec.snd.comp Primrec.snd) (Primrec.list_map (Primrec.snd.comp Primrec.snd) (Primrec.list_cons.comp (Primrec.fst.comp (Primrec.snd.comp Primrec.fst)) Primrec.snd).to₂) theorem seesRec {w : A → W} {t : A → List Event} (hw : Primrec w) (ht : Primrec t) : Primrec fun x => decide (sees (w x) (t x)) := by have v := P455GraphPrim.anyB (subsequencesRec.comp (eventsRec.comp hw)) ((Primrec.eq.comp (ht.comp (Primrec.fst (β := List Event))) Primrec.snd).decide.to₂) apply Primrec.of_eq v intro a apply Bool.eq_iff_iff.mpr simp [List.any_eq_true,sees,mem_subsequences] theorem bigramRec {w : A → W} {x y : A → Nat} (hw : Primrec w) (hx : Primrec x) (hy : Primrec y) : Primrec fun a => Problem455Swap.bigram (x a) (y a) (w a) := by let h (a : A) (p : Nat×W×Nat) := Problem455Swap.hit (x a) (y a) (some p.1) p.2.1.head? + p.2.2 have hh : Primrec₂ h := by apply Primrec₂.mk apply Primrec.nat_add.comp _ (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) apply Primrec.ite _ (.const 1) (.const 0) exact PrimrecPred.and (Primrec.eq.comp (Primrec.option_some.comp (Primrec.fst.comp Primrec.snd)) (Primrec.option_some.comp (hx.comp Primrec.fst))) (Primrec.eq.comp (Primrec.list_head?.comp (Primrec.fst.comp (Primrec.snd.comp Primrec.snd))) (Primrec.option_some.comp (hy.comp Primrec.fst))) apply (Primrec.list_rec hw (.const 0) hh).of_eq intro a induction w a with | nil => rfl | cons b t ih => exact congrArg (fun acc => h a (b,t,acc)) ih end P455WriterObservations end /- Begin Problem455WriterBinary (from finite-semigroup-identity-bases). -/ section namespace P455WriterBinary open P455PaddedTiles P455WriterTiles P455WriterProfiles abbrev Key := Nat × Bool def words (r : Nat) : List (List Nat) := Problem455Finite.wordsUpTo [0,1] (2*r) def atKey (r i : Nat) := (words r)[i]?.getD [] def key (i : P455BinaryProduct.Index r allow) : Key := (i.num.val,i.prof) theorem key_inj : Function.Injective (@key r allow) := by rintro ⟨a,b,_,_⟩ ⟨c,d,_,_⟩ e change (a.val,b)=(c.val,d) at e obtain ⟨h,rfl⟩ := Prod.mk.inj e cases Fin.ext h rfl def tests (r : Nat) (ts : Tags) (w : W) (prof : Bool) := P455EffectiveQMove.capB r w && decide (w=P455FirstTesters.power r ∨ 0 tests r ts (atKey r k.1) k.2) def spec (r : Nat) (k : Key) : P455Packed.Spec := (atKey r k.1, if k.2 then some [] else none) def bin (r : Nat) (ts : Tags) := (P455Table.distinct (filtered r ts)).map (spec r) theorem getAt (r : Nat) (i : Fin (words r).length) : atKey r i.val = (words r).get i := by simp [atKey,i.isLt] theorem valid (M : MachineTable n) (r ts) (tEq : ts = P455Enum.tags M) (w : W) (b : Bool) : tests r ts w b=true ↔ P455Closure.Cap r w ∧ (w=P455FirstTesters.power r ∨ 0 cases isProfile r (P455Enum.tags M) w <;> simp private theorem attachKeys {n : Nat} (xs : List (Fin n × Bool)) : xs.attach.map (fun x => (x.val.1.val,x.val.2)) = xs.map (fun x => (x.1.val,x.2)) := @List.attach_map_val (Fin n × Bool) Key xs (fun x => (x.1.val,x.2)) theorem raw_keys {n} (M : MachineTable n) (r : Nat) : (P455Enum.binary r M).list.map key = filtered r (P455Enum.tags M) := by let X := Fin (words r).length × Bool let K : X → Key := fun x => (x.1.val,x.2) let xs := choices (P455Enum.fins (words r).length).list P455Enum.bools.list have order : xs.map K = choices (List.range (words r).length) [false,true] := by unfold xs K rw [←p455MapFinRange] simp only [choices,P455Enum.fins,P455Enum.bools,List.map_flatMap,List.map_map,List.flatMap_map,Function.comp_def] unfold filtered rw [←order,List.filter_map] unfold P455Enum.binary simp only [P455Enum.Cover.map,P455Enum.coverSub,P455Enum.selectSub,List.map_map,Function.comp_def,key] rw [attachKeys] apply congrArg (List.map K) apply List.filter_congr intro a _ apply Bool.eq_iff_iff.mpr simp only [decide_eq_true_eq] rw [valid M r _ rfl] simp only [K,getAt,words] theorem bin_correct (M : MachineTable n) (r : Nat) : bin r (P455Enum.tags M) = P455Packed.names (P455Encoded.useCover (P455Enum.binary r M)) P455Packed.binSpec := by unfold bin rw [←raw_keys,←P455CataloguePrim.map_distinct key key_inj,List.map_map] unfold P455Packed.names P455Encoded.useCover apply List.map_congr_left intro i _ change (atKey r i.num.val,_) = _ rw [getAt] rfl variable {A : Type} [Primcodable A] theorem wordsRec : Primrec words := P455GraphPrim.wordsUpTo.comp (.const [0,1]) (Primrec.nat_mul.comp (.const 2) Primrec.id) theorem atKeyRec : Primrec₂ atKey := Primrec.option_getD.comp (Primrec.list_getElem?.comp (wordsRec.comp Primrec.fst) Primrec.snd) (.const []) theorem testsRec {r : A → Nat} {ts : A → Tags} {w : A → W} {b : A → Bool} (hr : Primrec r) (ht : Primrec ts) (hw : Primrec w) (hb : Primrec b) : Primrec fun a => tests (r a) (ts a) (w a) (b a) := by exact Primrec.and.comp (Primrec.and.comp (P455FrameProof.capCheck hr hw) (PrimrecPred.or (Primrec.eq.comp hw (replicateRec hr (.const 0))) (PrimrecPred.and (Primrec.nat_lt.comp (.const 0) (P455CataloguePrim.count'.comp hw (.const 0))) (Primrec.nat_lt.comp (.const 0) (P455CataloguePrim.count'.comp hw (.const 1))))).decide) (Primrec.eq.comp hb (isProfileRec hr ht hw)).decide theorem binRec {r : A → Nat} {ts : A → Tags} (hr : Primrec r) (ht : Primrec ts) : Primrec fun a => bin (r a) (ts a) := by have hg := choicesRec (Primrec.list_range.comp (Primrec.list_length.comp (wordsRec.comp hr))) (.const [false,true]) have k := Primrec.snd (α := A) (β := Key) have ha := Primrec.fst (α := A) (β := Key) have w := atKeyRec.comp (hr.comp ha) (Primrec.fst.comp k) have b := Primrec.snd.comp k have ft : Primrec₂ (fun a (k : Key) => tests (r a) (ts a) (atKey (r a) k.1) k.2) := testsRec (hr.comp ha) (ht.comp ha) w b have f : Primrec (fun a => filtered (r a) (ts a)) := P455GraphPrim.filter hg ft exact Primrec.list_map (P455CataloguePrim.distinct'.comp f) (Primrec.pair w (Primrec.ite (Primrec.eq.comp b (.const true)) (.const (some [])) (.const none))).to₂ end P455WriterBinary end /- Begin Problem455WriterCode (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram open P455EffectiveMachine P455MachineLocal P455MachineCleanup P455MachineTable def fromCodeBits (bits : List Bool) := machineData (raw (0::0::readBits bits)) theorem nums_code (C : Code ng nq) : readBits C.bits=C.numerals := by have h := read_many C.numerals [] have he : readBits []=[] := rfl simpa [Code.bits,he] using h theorem quote_machine (C : Code ng nq) (safe : C.Safe) : quote (C.machine safe)=C := by cases C with | mk m b s r => unfold quote apply congrArg (fun rows => Code.mk m b s rows) apply Vector.ext intro i hi apply Vector.ext intro j hj simp [quote,Code.machine,Code.read,Vector.get] theorem fromCodeBits_spec (C : Code ng nq) (safe : C.Safe) : P455WriterTiles.Models (fromCodeBits C.bits) (compile (normalized (C.machine safe))) := by have e : raw (0::0::readBits C.bits)=data (C.machine safe) := by rw [nums_code]; unfold data rowData; rw [quote_machine]; rfl unfold fromCodeBits; rw [e]; exact machineData_models _ end P455WriterProgram end /- Begin Problem455WriterMachinePrim (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram.Cert open Primrec variable {X : Type} [Primcodable X] theorem unpack' {ng k : X → Nat} (hg : Primrec ng) (hk : Primrec k) : Primrec fun x => unpack (ng x) (k x) := by have s := Primrec.nat_sub.comp hk (Primrec.const 1) have u := Primrec.nat_div.comp s (Primrec.const 3) exact (Primrec.nat_div.comp u hg).pair ((Primrec.nat_mod.comp u hg).pair (Primrec.nat_mod.comp s (Primrec.const 3))) theorem normalized' {m : X → Raw} {z a : X → Nat} (hm : Primrec m) (hz : Primrec z) (ha : Primrec a) : Primrec (fun x => normalizedIns (m x) (z x) (a x)) := by have ng := g'.comp hm have nq := q'.comp hm have k := (Primrec.list_getD 0).comp (entries'.comp hm) (Primrec.nat_add.comp (Primrec.nat_mul.comp hz ng) ha) exact Primrec.ite (Primrec.nat_lt.comp hz nq) (Primrec.ite (Primrec.eq.comp k (Primrec.const 0)) (nq.pair (ha.pair (Primrec.const 1))) (unpack' ng k)) (Primrec.ite ((Primrec.eq.comp hz nq).and ((Primrec.eq.comp ha (marker'.comp hm)).not)) (nq.pair (ha.pair (Primrec.const 0))) ((Primrec.nat_add.comp nq (Primrec.const 1)).pair (ha.pair (Primrec.const 1)))) theorem act' {m : X → Raw} {v : X → Nat} (hm : Primrec m) (hv : Primrec v) : Primrec (fun x => act (m x) (v x)) := by have ng := g'.comp hm have h := Primrec.nat_div.comp hv ng exact Primrec.ite (Primrec.nat_lt.comp (Primrec.const 0) h) (Primrec.option_some.comp (normalized' hm (Primrec.nat_sub.comp h (Primrec.const 1)) (Primrec.nat_mod.comp hv ng))) (Primrec.const none) theorem send' {ng a d : X → Nat} {i : X → Triple} (hg : Primrec ng) (ha : Primrec a) (hd : Primrec d) (hi : Primrec i) : Primrec (fun x => send (ng x) (a x) (d x) (i x)) := Primrec.nat_add.comp (Primrec.nat_mul.comp hg (Primrec.ite (Primrec.eq.comp (Primrec.snd.comp (Primrec.snd.comp hi)) hd) (Primrec.nat_add.comp (Primrec.fst.comp hi) (Primrec.const 1)) (Primrec.const 0))) ha def route (ng sym : Nat) (left right : Bool) (l c r : Option Triple) : Option Nat := if l=none ∧ c=none ∧ r=none then some sym else if l≠none ∧ c=none ∧ r=none then some (send ng sym 2 (l.getD (0,0,0))) else if l=none ∧ c=none ∧ r≠none then some (send ng sym 0 (r.getD (0,0,0))) else if l=none ∧ c≠none ∧ r=none then let i := c.getD (0,0,0) if (i.2.2=0 ∧ left=true) ∨ (i.2.2=2 ∧ right=true) then none else some (send ng i.2.1 1 i) else none theorem route_eq (n a : Nat) (b f : Bool) (l c r : Option Triple) : route n a b f l c r=output n a b f l c r := by cases l <;> cases c <;> cases r <;> rfl theorem output' {ng a : X → Nat} {bl br : X → Bool} {l c r : X → Option Triple} (hg : Primrec ng) (ha : Primrec a) (hb : Primrec bl) (hf : Primrec br) (hl : Primrec l) (hc : Primrec c) (hr : Primrec r) : Primrec fun x => output (ng x) (a x) (bl x) (br x) (l x) (c x) (r x) := by have L := Primrec.eq.comp hl (Primrec.const none) have C := Primrec.eq.comp hc (Primrec.const none) have R := Primrec.eq.comp hr (Primrec.const none) have i := Primrec.option_getD.comp hc (Primrec.const (0,0,0)) have D := Primrec.snd.comp (Primrec.snd.comp i) have rule : Primrec (fun x => route (ng x) (a x) (bl x) (br x) (l x) (c x) (r x)) := Primrec.ite (L.and (C.and R)) (Primrec.option_some.comp ha) (Primrec.ite (L.not.and (C.and R)) (Primrec.option_some.comp (send' hg ha (Primrec.const 2) (Primrec.option_getD.comp hl (Primrec.const (0,0,0))))) (Primrec.ite (L.and (C.and R.not)) (Primrec.option_some.comp (send' hg ha (Primrec.const 0) (Primrec.option_getD.comp hr (Primrec.const (0,0,0))))) (Primrec.ite (L.and (C.not.and R)) (Primrec.ite (((Primrec.eq.comp D (Primrec.const 0)).and (Primrec.eq.comp hb (Primrec.const true))).or ((Primrec.eq.comp D (Primrec.const 2)).and (Primrec.eq.comp hf (Primrec.const true)))) (Primrec.const none) (Primrec.option_some.comp (send' hg (Primrec.fst.comp (Primrec.snd.comp i)) (Primrec.const 1) i))) (Primrec.const none)))) exact rule.of_eq (fun _ => route_eq ..) theorem isNone' {A : Type} [Primcodable A] : Primrec (@Option.isNone A) := (Primrec.not.comp Primrec.option_isSome).of_eq fun o => by cases o <;> rfl theorem localValue' {m : X → Raw} {l r : X → Option Nat} {c : X → Nat} (hm : Primrec m) (hl : Primrec l) (hc : Primrec c) (hr : Primrec r) : Primrec fun x => localValue (m x) (l x) (c x) (r x) := output' (g'.comp hm) (Primrec.nat_mod.comp hc (g'.comp hm)) (isNone'.comp hl) (isNone'.comp hr) (Primrec.option_bind hl (act' (hm.comp Primrec.fst) Primrec.snd).to₂) (act' hm hc) (Primrec.option_bind hr (act' (hm.comp Primrec.fst) Primrec.snd).to₂) theorem dimension' : Primrec dimension := Primrec.nat_mul.comp g' (Primrec.nat_add.comp (Primrec.nat_add.comp q' (Primrec.const 2)) (Primrec.const 1)) theorem neighbour' : Primrec neighbour := Primrec.ite (Primrec.eq.comp Primrec.id (Primrec.const 0)) (Primrec.const none) (Primrec.option_some.comp (Primrec.nat_sub.comp Primrec.id (Primrec.const 1))) theorem line' {m : X → Raw} {n l c : X → Nat} (hm : Primrec m) (hn : Primrec n) (hl : Primrec l) (hc : Primrec c) : Primrec fun x => line (m x) (n x) (l x) (c x) := Primrec.list_map (Primrec.list_range.comp (Primrec.nat_add.comp hn (Primrec.const 1))) (localValue' (hm.comp Primrec.fst) (neighbour'.comp (hl.comp Primrec.fst)) (hc.comp Primrec.fst) (neighbour'.comp Primrec.snd)).to₂ theorem slab' {m : X → Raw} {n l : X → Nat} (hm : Primrec m) (hn : Primrec n) (hl : Primrec l) : Primrec fun x => slab (m x) (n x) (l x) := Primrec.list_flatMap (Primrec.list_range.comp hn) (line' (hm.comp Primrec.fst) (hn.comp Primrec.fst) (hl.comp Primrec.fst) Primrec.snd).to₂ theorem grid' {m : X → Raw} {n : X → Nat} (hm : Primrec m) (hn : Primrec n) : Primrec fun x => grid (m x) (n x) := Primrec.list_flatMap (Primrec.list_range.comp (Primrec.nat_add.comp hn (Primrec.const 1))) (slab' (hm.comp Primrec.fst) (hn.comp Primrec.fst) Primrec.snd).to₂ theorem machineData' : Primrec machineData := by have mark := Primrec.eq.comp (Primrec.nat_mod.comp (Primrec.snd (α:=Raw) (β:=Nat)) (g'.comp Primrec.fst)) (marker'.comp Primrec.fst) exact dimension'.pair ((Primrec.list_map (Primrec.list_range.comp dimension') mark.decide.to₂).pair (blank'.pair ((Primrec.nat_add.comp (Primrec.nat_mul.comp g' (Primrec.nat_add.comp start' (Primrec.const 1))) marker').pair ((Primrec.nat_add.comp (Primrec.nat_mul.comp g' (Primrec.nat_add.comp (Primrec.nat_add.comp q' (Primrec.const 1)) (Primrec.const 1))) marker').pair (grid' Primrec.id dimension'))))) theorem fromBits' : Primrec fromBits := machineData'.comp blankRaw' end P455WriterProgram.Cert end /- Begin Problem455WriterPhysical (from finite-semigroup-identity-bases). -/ section namespace P455WriterPhysical open P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine open P455EffectiveChain P455WriterFrontier P455WriterSweep /-- A finite-control producer may halt anywhere and leave arbitrary work on every track. Projecting cell j+1 has to recover the optional j-th output bit. -/ def Projects (M : Ordinary g q) (A : Alphabet M) (read : Fin g → Option Bool) (x y : List Bool) : Prop := ∃ t, let c := follow M (inputConfig M A x) t instruction M c=none ∧ ∀ j, read (c.tape (j+1)) = y[j]? def writer (M : Ordinary g q) (O : Alphabet M) (read : Fin g → Option Bool) := chain (monitor M) (sweep M O read) rfl def bits (M : Ordinary g q) (O : Alphabet M) (read : Fin g → Option Bool) (A : Alphabet M) : Alphabet (writer M O read) := liftAlphabet (monitor M) (sweep M O read) rfl (alphabet M A) theorem cleanup (M : Ordinary g q) (A O : Alphabet M) (read : Fin g → Option Bool) (empty : read M.blank=none) {x y} (hx : Projects M A read x y) : Delivers (writer M O read) (bits M O read A) x (writer M O read) (bits M O read O) y := by obtain ⟨t,halt,raw⟩ := hx let c := follow M (inputConfig M A x) t change instruction M c=none at halt change ∀ j, read (c.tape (j+1))=y[j]? at raw obtain ⟨n,ok,run⟩ := simulates M A x t change Good M c n at ok let src := tape n c.tape have proper : ∀ j, src j=ink M.marker ↔ j=0 := by intro j; by_cases le : j≤n · simp [src,tape,le,ink_inj,ok.2.2] · have ne : j≠0 := by omega simp [src,tape,le,ne,Ne.symm (ink_ne_fresh M.marker)] have used : ∀ i, i≤n → src i≠fresh g := by intro i le; simp [src,tape,le,ink_ne_fresh] have virgin : ∀ i, n cleanSym M O read (src j) let W := writer M O read let B := bits M O read O have output : dst=inputTape W B y := by funext j; cases j with | zero => change cleanSym M O read (src 0)=ink M.marker simp [cleanSym,(proper 0).mpr rfl] | succ j => change cleanSym M O read (src (j+1))=(y[j]?).elim (fresh g) (fun b => ink (O.bit b)) have ne := fun h => Nat.succ_ne_zero j ((proper _).mp h) by_cases le : j+1≤n · have e : src (j+1)=ink (c.tape (j+1)) := by simp [src,tape,le] simp [cleanSym,ne,e,ink_ne_fresh,raw,show ink (c.tape (j+1))≠ink M.marker from e ▸ ne] · have b := ok.2.1 (j+1) (Nat.lt_of_not_ge le) have v := virgin _ (Nat.lt_of_not_ge le) have nodata : y[j]?=none := (raw j).symm.trans (b ▸ empty) simp [cleanSym,v,nodata,Ne.symm (ink_ne_fresh M.marker)] let L := monitor M let R := sweep M O read let ci := inputConfig L (alphabet M A) x change follow L ci t=liftCfg n c at run have ended : instruction L (follow L ci t)=none := by rw [run,ins_eq M ok,halt]; rfl obtain ⟨j,stop,before⟩ := earliest (fun j => instruction L (follow L ci j)=none) t ended have same := (unique_halt L ci stop ended).trans run have ci_eq : inputConfig W (bits M O read A) x=rename (left 3) ci := rfl have switch : follow W (inputConfig W (bits M O read A) x) (j+1)= rename (right q) (⟨src,c.pos,0⟩ : Config (g+1) 3) := by rw [ci_eq,follow] change once (chain L R rfl) (follow (chain L R rfl) (rename (left 3) ci) j)=_ rw [follows_left L R rfl ci j before,shift_control L R rfl _ stop,same] rfl obtain ⟨⟨k,ex⟩,endR⟩ := finish M O read src c.pos n proper used virgin change follow R ⟨src,c.pos,0⟩ k=⟨dst,0,2⟩ at ex have final : follow W (inputConfig W (bits M O read A) x) (j+1+k)= rename (right q) (⟨dst,0,2⟩ : Config (g+1) 3) := by rw [follow_add,switch] exact (follows_right L R rfl _ k).trans (congrArg (rename (right q)) ex) refine ⟨j+1+k,?_⟩ dsimp only rw [final] refine ⟨?_,rfl,output⟩ change (chain L R rfl).delta (right q 2) (dst 0)=none change R.delta 2 (dst 0)=none at endR simp [chain,right_delta,endR] /-- Construction on a single producer, uniform in every input. -/ theorem writer_exists (M : Ordinary g q) (A O : Alphabet M) (read : Fin g → Option Bool) (empty : read M.blank=none) (allCodes : ∀ {k s} (P : Ordinary k s) (B : Alphabet P), ∃ X : P455Table.FiniteOps, Nonempty (P455Table.Presents X (P455MachineReduction.model (P455EffectiveWriter.diagonalInput P B).2)) ∧ Projects M A read (selfBits P B) (P455TableBits.encode (P455Table.matrix X))) : P455TableDecision.PresentationWriterExists := by refine ⟨_,_,writer M O read,bits M O read A,bits M O read O,?_⟩ intro k s P B obtain ⟨X,iso,h⟩ := allCodes P B exact ⟨X,iso,cleanup M A O read empty h⟩ end P455WriterPhysical end /- Begin Problem455TableValidate (from finite-semigroup-identity-bases). -/ section /- Validate a numeric output on all strings, including malformed machine codes. The test looks only at the finite square array and has primitive recursive bounds. -/ namespace P455TableValidate open P455Table P455TableSemantics def rows (T : Matrix) := T.all fun row => decide (row.length=T.length) && row.all fun x => decide (x (List.range T.length).all fun j => (List.range T.length).all fun k => decide (entry T (entry T i j) k=entry T i (entry T j k)) def unitB (T : Matrix) := (List.range T.length).any fun i => (List.range T.length).all fun j => decide (entry T i j=j) && decide (entry T j i=j) def valid (T : Matrix) := decide (0 assoc i hi j hj k hk⟩,u⟩ · rintro ⟨⟨ne,r,assoc⟩,u⟩; exact ⟨⟨⟨ne,r⟩,fun i hi j hj k hk => assoc i j k hi hj hk⟩,u⟩ theorem identity {T} (good : SemigroupTable T ∧ HasUnit T) : safe T=T := by simp [safe,(correct _).mpr good] theorem monoid (T) : SemigroupTable (safe T) ∧ HasUnit (safe T) := by unfold safe; split next h => exact (correct _).mp h next => exact (correct _).mp (by decide) theorem rowsRec : Primrec rows := by unfold rows apply P455FramePrim.allB Primrec.id apply Primrec₂.mk apply Primrec.and.comp (Primrec.eq.comp (Primrec.list_length.comp Primrec.snd) (Primrec.list_length.comp Primrec.fst)).decide apply P455FramePrim.allB Primrec.snd apply Primrec₂.mk exact (Primrec.nat_lt.comp Primrec.snd (Primrec.list_length.comp (Primrec.fst.comp Primrec.fst))).decide theorem assocRec : Primrec assocB := by unfold assocB have n : Primrec fun T : Matrix => List.range T.length := Primrec.list_range.comp Primrec.list_length apply P455FramePrim.allB n apply Primrec₂.mk apply P455FramePrim.allB (n.comp Primrec.fst) apply Primrec₂.mk apply P455FramePrim.allB (n.comp (Primrec.fst.comp Primrec.fst)) apply Primrec₂.mk refine (Primrec.eq.comp ?_ ?_).decide · apply P455NumericProductPrim.entry' ((Primrec.fst.comp Primrec.fst).comp Primrec.fst) _ Primrec.snd exact P455NumericProductPrim.entry' ((Primrec.fst.comp Primrec.fst).comp Primrec.fst) ((Primrec.snd.comp Primrec.fst).comp Primrec.fst) (Primrec.snd.comp Primrec.fst) · apply P455NumericProductPrim.entry' ((Primrec.fst.comp Primrec.fst).comp Primrec.fst) ((Primrec.snd.comp Primrec.fst).comp Primrec.fst) exact P455NumericProductPrim.entry' ((Primrec.fst.comp Primrec.fst).comp Primrec.fst) (Primrec.snd.comp Primrec.fst) Primrec.snd theorem unitRec : Primrec unitB := by unfold unitB have n : Primrec fun T : Matrix => List.range T.length := Primrec.list_range.comp Primrec.list_length apply P455GraphPrim.anyB n apply Primrec₂.mk apply P455FramePrim.allB (n.comp Primrec.fst) apply Primrec₂.mk exact Primrec.and.comp (Primrec.eq.comp (P455NumericProductPrim.entry' (Primrec.fst.comp Primrec.fst) (Primrec.snd.comp Primrec.fst) Primrec.snd) Primrec.snd).decide (Primrec.eq.comp (P455NumericProductPrim.entry' (Primrec.fst.comp Primrec.fst) Primrec.snd (Primrec.snd.comp Primrec.fst)) Primrec.snd).decide theorem validRec : Primrec valid := Primrec.and.comp (Primrec.and.comp (Primrec.and.comp (Primrec.nat_lt.comp (Primrec.const 0) Primrec.list_length).decide rowsRec) assocRec) unitRec theorem safeRec : Primrec safe := Primrec.ite (Primrec.eq.comp validRec (Primrec.const true)) Primrec.id (Primrec.const [[0]]) end P455TableValidate end /- Begin Problem455BooleanReader (from finite-semigroup-identity-bases). -/ section namespace P455BooleanReader open P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine open P455EffectiveChain P455RelabeledChain P455Table P455TableBits P455TableSemantics def delta (q a : Fin 4) : Option (Ins (Fin 4) (Fin 4)) := if q=0 then some ⟨1,a,.right⟩ else if q=1 then some ⟨if a=3 then 3 else 2,a,.stay⟩ else none def reader : Ordinary 4 4 where marker := 0 blank := 1 blank_ne := by decide start := 0 delta := delta keeps := by intro s a i h unfold delta at h split at h · cases h; rfl · split at h · cases h; rfl · contradiction leftSafe := by intro s i h unfold delta at h split at h · cases h; decide · split at h · cases h; decide · contradiction def bits : Alphabet reader where bit b := if b then 3 else 2 ink b := by cases b <;> decide away b := by cases b <;> decide distinct := by decide def ans (q : Fin 4) := decide (q=3) theorem reads_bit (b : Bool) : Answers reader bits ans [b] b := by cases b <;> exact ⟨2,rfl,rfl⟩ /-- This bit-string decider is total, but only its answers on serialized finite semigroups are constrained. -/ def StandardDecider := ∃ f : List Bool → Bool, Computable f ∧ ∀ T : Matrix, SemigroupTable T → (f (encode T)=true ↔ P455PureSemigroup.Basis T) /-- A partial algorithm may be undefined or wrong off the promise. -/ def PromiseDecider := ∃ f : List Bool →. Bool, Partrec f ∧ ∀ T : Matrix, SemigroupTable T → ∃ b ∈ f (encode T), (b=true ↔ P455PureSemigroup.Basis T) end P455BooleanReader end /- Begin Problem455StatementAudit (from finite-semigroup-identity-bases). -/ section namespace P455StatementAudit open P455Table P455TableSemantics P455BinaryTerms P455BinaryBasis P455PureSemigroup def product (T : Matrix) (valid : SemigroupTable T) (a b : Fin T.length) : Fin T.length := ⟨entry T a b,entry_lt valid a.isLt b.isLt⟩ def val {T : Matrix} (ok : SemigroupTable T) (f : Nat → Fin T.length) : Term → Fin T.length | .var x => f x | .mul s t => product T ok (val ok f s) (val ok f t) theorem eval_fin {T : Matrix} (ok : SemigroupTable T) (f : Nat → Fin T.length) (s : Term) : (val ok f s).val=eval T (fun x => (f x).val) s := by induction s <;> simp_all [val,eval,product] theorem assignments {T : Matrix} (ok : SemigroupTable T) (s t : Term) : ValidTerm T s t ↔ ∀ f : Nat → Fin T.length, val ok f s=val ok f t := by constructor · intro all f apply Fin.ext rw [eval_fin,eval_fin] exact all _ (fun x => (f x).isLt) · intro h f bounded let g (i : Nat) : Fin T.length := ⟨f i,bounded i⟩ simpa only [eval_fin,g] using congrArg Fin.val (h g) theorem substitution {T : Matrix} (ok : SemigroupTable T) (g : Nat → Term) (f : Nat → Fin T.length) (s : Term) : val ok f (inst g s) = val ok (fun x => val ok f (g x)) s := by induction s <;> simp_all [inst,val] theorem soundness {T : Matrix} (ok : SemigroupTable T) {G : Term → Term → Prop} (laws : ∀ {a b}, G a b → ValidTerm T a b) {s t} (p : Equational G s t) : ValidTerm T s t := by apply (assignments ok _ _).mpr induction p with | refl => exact fun _ => rfl | gen h => exact (assignments ok _ _).mp (laws h) | symm _ ih => exact fun f => (ih f).symm | trans _ _ ih ik => exact fun f => (ih f).trans (ik f) | mul _ _ ih ik => intro f; simp only [val,ih f,ik f] | subst g _ ih => intro f; rw [substitution,substitution]; exact ih _ /-- Exact equality between the identities holding in a semigroup and the ordinary consequences of one finite list of two-sided equations. -/ theorem exact_basis {T : Matrix} (ok : SemigroupTable T) : Basis T ↔ ∃ R : List (Term × Term), ∀ s t, (∀ f : Nat → Fin T.length, val ok f s=val ok f t) ↔ Equational (fun u v => (u,v) ∈ R) s t := by constructor · rintro ⟨R,truth,complete⟩ exact ⟨R,fun s t => ⟨fun h => complete s t ((assignments ok s t).mpr h), fun pf => (assignments ok s t).mp (soundness ok (fun h => truth _ _ h) pf)⟩⟩ · rintro ⟨R,exactness⟩ exact ⟨R,fun s t h => (assignments ok _ _).mpr ((exactness _ _).mpr (.gen h)), fun s t h => (exactness _ _).mp ((assignments ok s t).mp h)⟩ theorem encoding_inj {S T : Matrix} (s : SemigroupTable S) (t : SemigroupTable T) (h : P455TableBits.encode S=P455TableBits.encode T) : S=T := by have x := P455TableBits.roundtrip (fun r hr => (s.2.1 r hr).1) have y := P455TableBits.roundtrip (fun r hr => (t.2.1 r hr).1) exact Option.some.inj (x.symm.trans ((congrArg P455TableBits.parse h).trans y)) end P455StatementAudit end /- Begin Problem455WriterBlockTest (from finite-semigroup-identity-bases). -/ section namespace P455WriterBlocks open Problem455Swap P455WriterTiles P455WriterProfiles P455WriterObservations def stable (r : Nat) (w s : W) := (choices s w).all fun p => decide ((bigram p.1 p.2 w=r ∨ bigram p.2 p.1 w=r) → p.2∈s) theorem stable_ok (r : Nat) (w s : W) : stable r w s=true ↔ P455Enum.stable r w s := by simp only [stable,P455Enum.stable,choices,List.all_eq_true,List.mem_flatMap,List.mem_map,decide_eq_true_eq,Link] constructor · intro h a i b j exact h (a,b) ⟨a,i,b,j,rfl⟩ · rintro h _ ⟨a,i,b,j,rfl⟩ exact h a i b j def joined (r : Nat) (w : W) (x y : Nat) := let v := x::w (Problem455Finite.wordsUpTo v v.length).all fun s => decide (x∈s → stable r w s=true → y∈s) theorem joined_ok {r : Nat} (hr : 0 decide (Joined (Link r w) x a)) have mem {a} : a∈s ↔ a∈v ∧ Joined (Link r w) x a := by simp [s] have ins : s∈Problem455Finite.wordsUpTo v v.length := Problem455Finite.covered _ _ _ (List.length_filter_le ..) (fun _ m => (mem.mp m).1) have st : P455Enum.stable r w s := fun _ ma _ mb ed => mem.mpr ⟨List.mem_cons_of_mem _ mb,.extend (mem.mp ma).2 ed⟩ exact (mem.mp (closed s ins (mem.mpr ⟨List.mem_cons_self,.refl _⟩) st)).2 · intro path s _ start st induction path with | refl => exact start | extend p ed ih => exact st _ ih _ (ed.elim (fun h => (P455Enum.linkNames hr h).2) (fun h => (P455Enum.linkNames hr h).1)) ed def same (r : Nat) (w : W) (x y : Nat) := decide (w.count x=r ∧ w.count y=r) && joined r w x y theorem same_ok {r : Nat} (hr : 0 stable (r a) (w a) (s a) := by apply P455FramePrim.allB (choicesRec hs hw) apply Primrec₂.mk have p := Primrec.snd (α := A) (β := Nat × Nat) have a := Primrec.fst.comp p have b := Primrec.snd.comp p have xy := Primrec.eq.comp (bigramRec (hw.comp Primrec.fst) a b) (hr.comp Primrec.fst) have yx := Primrec.eq.comp (bigramRec (hw.comp Primrec.fst) b a) (hr.comp Primrec.fst) exact (impliesRec (PrimrecPred.or xy yx) (P455CataloguePrim.mem'.comp b (hs.comp Primrec.fst))).decide theorem joinedRec {r x y : A → Nat} {w : A → W} (hr : Primrec r) (hw : Primrec w) (hx : Primrec x) (hy : Primrec y) : Primrec fun a => joined (r a) (w a) (x a) (y a) := by have v := Primrec.list_cons.comp hx hw unfold joined apply P455FramePrim.allB (p := fun a s => decide (x a∈s → stable (r a) (w a) s=true → y a∈s)) (P455GraphPrim.wordsUpTo.comp v (Primrec.list_length.comp v)) apply Primrec₂.mk have s := Primrec.snd (α := A) (β := W) exact (impliesRec (P455CataloguePrim.mem'.comp (hx.comp Primrec.fst) s) (impliesRec (Primrec.eq.comp (stableRec (hr.comp Primrec.fst) (hw.comp Primrec.fst) s) (.const true)) (P455CataloguePrim.mem'.comp (hy.comp Primrec.fst) s))).decide theorem sameRec {r x y : A → Nat} {w : A → W} (hr : Primrec r) (hw : Primrec w) (hx : Primrec x) (hy : Primrec y) : Primrec fun a => same (r a) (w a) (x a) (y a) := Primrec.and.comp (PrimrecPred.and (Primrec.eq.comp (P455CataloguePrim.count'.comp hw hx) hr) (Primrec.eq.comp (P455CataloguePrim.count'.comp hw hy) hr)).decide (joinedRec hr hw hx hy) end P455WriterBlocks end /- Begin Problem455WriterStructuralTests (from finite-semigroup-identity-bases). -/ section namespace P455WriterStructural open P455WriterTiles P455WriterProfiles P455WriterObservations P455PaddedTiles open P455Structural (Rec Edge Intrusion Width Overlap) open Problem455.Slots local instance (w : W) (p : List Event) : Decidable (sees w p) := P455Enum.seesD w p def recordB (r : Nat) (ts : Tags) (w : W) (a b : Nat) := decide (a≠b) && (choices ts [false,true]).any (fun tb => decide (tb.1.length+16=r ∧ select [a,b] w=profile a b tb.1 tb.2)) def edgeB (r : Nat) (ts : Tags) (w : W) (a b : Nat) := recordB r ts w a b || recordB r ts w b a theorem record_correct (M : MachineTable n) (r w a b) : recordB r (P455Enum.tags M) w a b=true ↔ Rec w r (allowed M) a b := by simp only [recordB,choices,List.any_eq_true,List.mem_flatMap,List.mem_map,Bool.and_eq_true,decide_eq_true_eq] constructor · rintro ⟨hne,_,⟨t,mt,bit,_,rfl⟩,le,eq⟩ exact ⟨t,hne,le,P455Enum.mem_tags.mp mt,bit,eq⟩ · rintro ⟨t,hne,le,mt,bit,eq⟩ refine ⟨hne,(t,bit),⟨t,P455Enum.mem_tags.mpr mt,bit,?_,rfl⟩,le,eq⟩ cases bit <;> simp theorem edge_correct (M : MachineTable n) (r w a b) : edgeB r (P455Enum.tags M) w a b=true ↔ Edge w r (allowed M) a b := by simp only [edgeB,Bool.or_eq_true,record_correct,Edge] def widthB (k : Nat) (w : W) := (Problem455Finite.wordsUpTo w k).any fun c => w.all fun x => decide (x∈c) theorem width_correct (k : Nat) (w : W) : widthB k w=true ↔ Width k w := by simp only [widthB,List.any_eq_true,List.all_eq_true,decide_eq_true_eq] constructor · rintro ⟨c,m,h⟩ exact ⟨c,P455Enum.words_bound _ _ m,h⟩ · rintro ⟨c,lim,h⟩ let t := c.filter fun x => x∈w have cover (x) (m : x∈w) : x∈t := by simp [t,h x m,m] exact ⟨t,Problem455Finite.covered _ _ t ((List.length_filter_le ..).trans lim) (fun _ m => of_decide_eq_true (List.mem_filter.mp m).2),cover⟩ def overlapB (r : Nat) (ts : Tags) (w : W) := (choices w (choices w w)).any fun k => decide (k.1≠k.2.1 ∧ k.1≠k.2.2 ∧ k.2.1≠k.2.2) && edgeB r ts w k.1 k.2.1 && edgeB r ts w k.1 k.2.2 theorem overlap_correct (M : MachineTable n) (r w) : overlapB r (P455Enum.tags M) w=true ↔ Overlap w r (allowed M) := by simp only [overlapB,choices,List.any_eq_true,List.mem_flatMap,List.mem_map,Bool.and_eq_true, decide_eq_true_eq,edge_correct] constructor · rintro ⟨_,⟨o,_,_,⟨p,_,q,_,rfl⟩,rfl⟩,⟨⟨op,oq,pq⟩,ep⟩,eq⟩ exact ⟨o,p,q,op,oq,pq,ep,eq⟩ · rintro ⟨o,p,q,op,oq,pq,ep,eq⟩ exact ⟨_,⟨o,(P455Enum.edge_names ep).1,_,⟨p,(P455Enum.edge_names ep).2,q,(P455Enum.edge_names eq).2,rfl⟩,rfl⟩, ⟨⟨op,oq,pq⟩,ep⟩,eq⟩ def intrusionB (r : Nat) (ts : Tags) (w : W) := (choices w (choices w (events w))).any fun k => decide (k.1≠k.2.1 ∧ k.2.2.1≠k.1 ∧ k.2.2.1≠k.2.1) && recordB r ts w k.1 k.2.1 && decide (sees w [(k.1,0),k.2.2,(k.2.1,2)]) theorem intrusion_correct (M : MachineTable n) (r w) : intrusionB r (P455Enum.tags M) w=true ↔ Intrusion w r (allowed M) := by simp only [intrusionB,choices,List.any_eq_true,List.mem_flatMap,List.mem_map,Bool.and_eq_true, decide_eq_true_eq,record_correct] constructor · rintro ⟨_,⟨o,_,_,⟨p,_,e,_,rfl⟩,rfl⟩,⟨⟨op,zo,zp⟩,recProof⟩,s⟩ exact ⟨o,p,e.1,e.2,op,zo,zp,recProof,s⟩ · rintro ⟨o,p,z,j,op,zo,zp,recProof,s⟩ exact ⟨_,⟨o,(P455Enum.rec_names recProof).1,_,⟨p,(P455Enum.rec_names recProof).2,(z,j),s.subset (by simp),rfl⟩,rfl⟩, ⟨⟨op,zo,zp⟩,recProof⟩,s⟩ def compressedB (r : Nat) (w : W) := (choices w w).all fun p => decide (Problem455Swap.bigram p.1 p.2 w ≠ r) theorem compressed_correct {r : Nat} (pos : 0 ok (atKey r k.1) k.2 def asSpec (r : Nat) (k : Key) : P455Packed.Spec := (atKey r k.1,some [(k.2.1,k.2.2.1),(k.2.2.2.1,k.2.2.2.2)]) def family (r : Nat) (ok : Predicate) := (P455Table.distinct (filtered r ok)).map (asSpec r) def ValidKey (M : MachineTable n) (r : Nat) (w : List Nat) (k : Quad) : Prop := P455Closure.Cap r w ∧ ∃ e : EdgeCertificate, e.a.owner=k.1 ∧ e.a.mate=k.2.1 ∧ e.b.owner=k.2.2.1 ∧ e.b.mate=k.2.2.2 ∧ (∀ x, x∈w ↔ x∈P455EdgeProjection.names (system n) e) ∧ Holds r (allowed M) (P455EdgeProduct.marks k.1 k.2.1 k.2.2.1 k.2.2.2) w (e.query (system n)) theorem getAt (r : Nat) (i : Fin (P455EdgeProduct.words r).length) : atKey r i.val=(P455EdgeProduct.words r).get i := by simp [atKey,i.isLt] def vals (x : P455Enum.EdgeKey r) : Key := (x.1.val,x.2.1.val,x.2.2.1.val,x.2.2.2.1.val,x.2.2.2.2.val) private theorem attachKeys (xs : List (P455Enum.EdgeKey r)) : xs.attach.map (fun x => vals x.val) = xs.map vals := List.attach_map_val .. theorem filtered_correct (M : MachineTable n) (hr : 0 @vals r x.val) (List.attach (_ : List (P455Enum.EdgeKey r))))=_ rw [@attachKeys r] apply congrArg (List.map vals); apply List.filter_congr intro x _; apply Bool.eq_iff_iff.mpr simp only [decide_eq_true_eq,correct,vals,getAt,ValidKey] theorem family_correct (M : MachineTable n) (hr : 0 ok p.1.1 p.1.2 p.2)) : Primrec fun x => family (r x) (ok x) := by have ks := choicesRec (Primrec.list_range.comp (Primrec.list_length.comp (wordsRec.comp hr))) (.const quads) have src := Primrec.fst (α:=A) (β:=Key) have k := Primrec.snd (α:=A) (β:=Key) have w := atKeyRec.comp (hr.comp src) (Primrec.fst.comp k) have z := Primrec.snd.comp k have f : Primrec (fun x => filtered (r x) (ok x)) := P455GraphPrim.filter ks (h.comp ((src.pair w).pair z)).to₂ have t := Primrec.snd.comp z have u := Primrec.snd.comp t have ab := (Primrec.fst.comp z).pair (Primrec.fst.comp t) exact Primrec.list_map (P455CataloguePrim.distinct'.comp f) (w.pair (Primrec.option_some.comp (Primrec.list_cons.comp ab (Primrec.list_cons.comp u (.const []))))).to₂ end P455WriterEdge end /- Begin Problem455WriterCodePrim (from finite-semigroup-identity-bases). -/ section namespace P455WriterProgram.Cert theorem fromCodeBits' : Primrec fromCodeBits := machineData'.comp (raw'.comp (Primrec.list_cons.comp (Primrec.const 0) (Primrec.list_cons.comp (Primrec.const 0) readBits'))) end P455WriterProgram.Cert end /- Begin Problem455FoldWorld (from finite-semigroup-identity-bases). -/ section /- The left physical marker stores no data. The two virtual cells above it stay in finite control. At position p>0 the left and right tracks carry virtual positions -p and p+1, respectively. -/ namespace P455FoldWorld open Turing P455MachineLocal P455MachineTable def coord : Bool → Nat → Int | false,p => -(p : Int) | true,p => (p : Int)+1 def motion (s : Bool) (atMark : Bool) (dir : Turing.Dir) : Bool × Direction := match s,dir with | false,.left => (false,.right) | false,.right => if atMark then (true,.stay) else (false,.left) | true,.right => (true,.right) | true,.left => if atMark then (false,.stay) else (true,.left) theorem moves (s p d) : let m := motion s (decide (p=0)) d coord m.1 (dest m.2 p)=coord s p + (if d=.right then 1 else -1) := by cases s <;> cases d <;> cases p <;> simp [coord,motion,dest] omega structure World (Γ Q : Type) where store : Int→Γ side : Bool radius : Nat state : Q def pos (w : World Γ Q) := coord w.side w.radius def act (w : World Γ Q) (z : Q) (i : TM0.Stmt Γ) : World Γ Q := match i with | .move d => let m := motion w.side (decide (w.radius=0)) d ⟨w.store,m.1,dest m.2 w.radius,z⟩ | .write b => ⟨Function.update w.store (pos w) b,w.side,w.radius,z⟩ def packed (f : Int→Γ) (p : Nat) := (f (coord false p),f (coord true p)) def choose (side : Bool) (pair : Γ×Γ) := if side then pair.2 else pair.1 def put (side : Bool) (pair : Γ×Γ) (a : Γ) := if side then (pair.1,a) else (a,pair.2) theorem choose_packed (s : Bool) (f : Int→Γ) (p) : choose s (packed f p)=f (coord s p) := by cases s <;> rfl theorem put_packed (s : Bool) (f : Int→Γ) (p : Nat) (a) (j : Nat) : packed (Function.update f (coord s p) a) j= if j=p then put s (packed f p) a else packed f j := by by_cases e : j=p · subst j; cases s <;> simp [coord,put,packed,Function.update_apply] <;> intro h <;> omega · have same1 : - (j : Int) ≠ -(p : Int) := by omega have same2 : (j : Int)+1 ≠ (p : Int)+1 := by omega have cross1 : -(j : Int) ≠ (p : Int)+1 := by omega have cross2 : (j : Int)+1 ≠ -(p : Int) := by omega cases s <;> simp [coord,put,packed,e,Function.update_apply,same1,same2,cross1,cross2] /-- The absolute tape retains the origin, which a bare bilateral configuration forgets. -/ def Describes [Inhabited Γ] (w : World Γ Q) (c : TM0.Cfg Γ Q) := w.state=c.q ∧ ∀ i : Int, c.Tape.nth i=w.store (pos w+i) theorem act_describes [Inhabited Γ] {w : World Γ Q} {c : TM0.Cfg Γ Q} (h : Describes w c) (z : Q) (i : TM0.Stmt Γ) : Describes (act w z i) ⟨z,match i with | .move d => c.Tape.move d | .write b => c.Tape.write b⟩ := by cases i with | write b => refine ⟨rfl,fun j => ?_⟩ simp only [Tape.write_nth,act,pos,Function.update_apply] by_cases e : j=0 · simp [e] · have ne : coord w.side w.radius+j≠coord w.side w.radius := by omega simpa only [if_neg e,if_neg ne,pos] using h.2 j | move d => refine ⟨rfl,fun j => ?_⟩ have mv := moves w.side w.radius d cases d <;> simp only [Tape.move_left_nth,Tape.move_right_nth,act,pos] at * · rw [h.2]; congr 1; dsimp [pos] at *; omega · rw [h.2]; congr 1; dsimp [pos] at *; omega end P455FoldWorld end /- Begin Problem455SemanticConsequence (from finite-semigroup-identity-bases). -/ section namespace P455SemanticConsequence open P455BinaryTerms P455PureSemigroup def ev (mul : A → A → A) (f : Nat → A) : Term → A | .var i => f i | .mul s t => mul (ev mul f s) (ev mul f t) def satisfies (mul : A → A → A) (s t : Term) := ∀ f : Nat → A, ev mul f s=ev mul f t def entails (R : Term → Term → Prop) (s t : Term) := ∀ (A : Type) (mul : A → A → A), (∀ u v, R u v → satisfies mul u v) → satisfies mul s t theorem ev_sub (mul : A → A → A) (f : Nat → A) (g : Nat → Term) (s : Term) : ev mul f (inst g s)=ev mul (fun i => ev mul f (g i)) s := by induction s <;> simp_all [inst,ev] theorem sound {R s t} (h : Equational R s t) : entails R s t := by intro A mul models induction h with | refl => exact fun _ => rfl | gen g => exact models _ _ g | symm _ ih => exact fun f => (ih f).symm | trans _ _ ih ik => exact fun f => (ih f).trans (ik f) | mul _ _ ih ik => intro f; simp only [ev,ih f,ik f] | subst g _ ih => intro f; rw [ev_sub,ev_sub]; exact ih _ def relation (R : Term → Term → Prop) : Setoid Term where r := Equational R iseqv := ⟨fun t => .refl t, fun h => .symm h,fun h k => .trans h k⟩ abbrev Free (R) := Quotient (relation R) def cls (R) (t : Term) : Free R := Quotient.mk _ t def product (R) (a b : Free R) : Free R := Quotient.liftOn₂ a b (fun u v => cls R (.mul u v)) (fun _ _ _ _ h k => Quotient.sound (Equational.mul h k)) theorem ev_class (R) (g : Nat → Term) (t) : ev (product R) (fun i => cls R (g i)) t=cls R (inst g t) := by induction t <;> simp_all [ev,inst]; rfl theorem free_model (R) (s t) (h : R s t) : satisfies (product R) s t := by intro f let g i := Classical.choose (Quotient.exists_rep (f i)) have eq : f=fun i => cls R (g i) := funext fun i => (Classical.choose_spec (Quotient.exists_rep (f i))).symm rw [eq, ev_class, ev_class] exact Quotient.sound (Equational.subst g (.gen h)) theorem id_inst (t : Term) : inst Term.var t=t := by induction t <;> simp_all [inst] theorem complete {R s t} (h : entails R s t) : Equational R s t := by have e := h (Free R) (product R) (free_model R) (fun i => cls R (.var i)) have eq : cls R s=cls R t := by simpa only [ev_class,id_inst] using e exact Quotient.exact eq theorem iff_semantic (R) (s t) : Equational R s t ↔ entails R s t := ⟨sound,complete⟩ theorem public_basis {T : P455Table.Matrix} (ok : P455TableSemantics.SemigroupTable T) : Basis T ↔ ∃ R : List (Term × Term), ∀ s t, (∀ f : Nat → Fin T.length, P455StatementAudit.val ok f s=P455StatementAudit.val ok f t) ↔ entails (fun u v => (u,v) ∈ R) s t := by rw [P455StatementAudit.exact_basis ok] simp only [iff_semantic] end P455SemanticConsequence end /- Begin Problem455WriterQueryLeaves (from finite-semigroup-identity-bases). -/ section namespace P455WriterQueryLeaves open P455WriterTiles P455WriterProfiles P455WriterObservations Problem455.Slots open P455Witness (Query Holds Tag Marking) abbrev Env := Nat × Tags × List (Nat×Nat) × W structure ModelsEnv (e : Env) (r : Nat) (allow : Tag → Prop) (mark : Marking) (w : W) : Prop where lim : e.1=r tags : ∀ t, t∈e.2.1 ↔ allow t marks : ∀ a b, (a,b)∈e.2.2.1 ↔ mark a b word : e.2.2.2=w pos : 0 decide (p.2 ≠ e.1-2)) && decide (sees e.2.2.2 pat) def separate (e : Env) (a b : Nat) := !(P455WriterBlocks.same e.1 e.2.2.2 a b) def earlyBefore (e : Env) (xs ys : W) := (choices xs ys).all fun p => order e [(p.1,2),(p.2,0)] def earlyDisjoint (e : Env) (xs ys : W) := earlyBefore e xs ys || earlyBefore e ys xs variable {e : Env} {r : Nat} {allow : Tag → Prop} {mark : Marking} {w : W} theorem record_ok (h : ModelsEnv e r allow mark w) (a b t) : record e a b t=true ↔ Holds r allow mark w (.record a b t) := by simp only [record,good,matched,Bool.and_eq_true,Bool.or_eq_true,decide_eq_true_eq,h.lim,h.word,h.tags,Holds,typed] constructor · rintro ⟨⟨ne,len,ok⟩,u|v⟩ · exact ⟨ne,len,ok,false,u⟩ · exact ⟨ne,len,ok,true,v⟩ · rintro ⟨ne,len,ok,bit,z⟩ exact ⟨⟨ne,len,ok⟩,by cases bit <;> simp_all⟩ theorem marked_ok (h : ModelsEnv e r allow mark w) (a b t bit) : marked e a b t bit=true ↔ Holds r allow mark w (.markedBit a b t bit) := by simp only [marked,good,matched,Bool.and_eq_true,decide_eq_true_eq,h.lim,h.word,h.tags,h.marks,Holds,and_assoc] theorem order_ok (h : ModelsEnv e r allow mark w) (pat) : order e pat=true ↔ Holds r allow mark w (.order pat) := by simp only [order,Bool.and_eq_true,List.all_eq_true,decide_eq_true_eq,h.lim,h.word,Holds] theorem separate_ok (h : ModelsEnv e r allow mark w) (a b) : separate e a b=true ↔ Holds r allow mark w (.separate a b) := by simp only [separate,Bool.not_eq_true',Holds,h.lim,h.word,←P455WriterBlocks.same_ok h.pos] cases P455WriterBlocks.same r w a b <;> simp theorem earlyBefore_ok (h : ModelsEnv e r allow mark w) (xs ys) : earlyBefore e xs ys=true ↔ Holds r allow mark w (P455Witness.earlyBefore xs ys) := by rw [P455PortReflection.earlyBefore_iff] simp only [earlyBefore,choices,List.all_eq_true,List.mem_flatMap,List.mem_map] constructor · intro t a ha b hb exact (order_ok h _).mp (t (a,b) ⟨a,ha,b,hb,rfl⟩) · rintro t _ ⟨a,ha,b,hb,rfl⟩ exact (order_ok h _).mpr (t a ha b hb) theorem earlyDisjoint_ok (h : ModelsEnv e r allow mark w) (xs ys) : earlyDisjoint e xs ys=true ↔ Holds r allow mark w (P455Witness.earlyDisjoint xs ys) := by simp only [earlyDisjoint,Bool.or_eq_true,earlyBefore_ok h,P455Witness.earlyDisjoint,Holds] variable {A X : Type} [Primcodable A] [Primcodable X] theorem memRec [DecidableEq X] {x : A → X} {l : A → List X} [inst : ∀ a, Decidable (x a∈l a)] (hx : Primrec x) (hl : Primrec l) : Primrec fun a => @decide _ (inst a) := by have v := P455GraphPrim.anyB hl ((Primrec.eq.comp (hx.comp (Primrec.fst (β := X))) Primrec.snd).decide.to₂) apply Primrec.of_eq v intro a apply Bool.eq_iff_iff.mpr simp [List.any_eq_true] theorem limRec {f : A → Env} (hf : Primrec f) : Primrec fun x => (f x).1 := Primrec.fst.comp hf theorem tagsRec {f : A → Env} (hf : Primrec f) : Primrec fun x => (f x).2.1 := Primrec.fst.comp (Primrec.snd.comp hf) theorem marksRec {f : A → Env} (hf : Primrec f) : Primrec fun x => (f x).2.2.1 := Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp hf)) theorem wordRec {f : A → Env} (hf : Primrec f) : Primrec fun x => (f x).2.2.2 := Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp hf)) theorem matchedRec {f : A → Env} {a b : A → Nat} {t : A → Tag} {v : A → Bool} (hf : Primrec f) (ha : Primrec a) (hb : Primrec b) (ht : Primrec t) (hv : Primrec v) : Primrec fun x => matched (f x) (a x) (b x) (t x) (v x) := (Primrec.eq.comp (selectRec (Primrec.list_cons.comp ha (Primrec.list_cons.comp hb (.const []))) (wordRec hf)) (profileRec ha hb ht hv)).decide theorem goodRec {f : A → Env} {a b : A → Nat} {t : A → Tag} (hf : Primrec f) (ha : Primrec a) (hb : Primrec b) (ht : Primrec t) : Primrec fun x => good (f x) (a x) (b x) (t x) := (PrimrecPred.and (PrimrecPred.not (Primrec.eq.comp ha hb)) (PrimrecPred.and (Primrec.eq.comp (Primrec.nat_add.comp (Primrec.list_length.comp ht) (.const 16)) (limRec hf)) (memRec ht (tagsRec hf)).primrecPred)).decide theorem recordRec {f : A → Env} {a b : A → Nat} {t : A → Tag} (hf : Primrec f) (ha : Primrec a) (hb : Primrec b) (ht : Primrec t) : Primrec fun x => record (f x) (a x) (b x) (t x) := Primrec.and.comp (goodRec hf ha hb ht) (Primrec.or.comp (matchedRec hf ha hb ht (.const false)) (matchedRec hf ha hb ht (.const true))) theorem markedRec {f : A → Env} {a b : A → Nat} {t : A → Tag} {v : A → Bool} (hf : Primrec f) (ha : Primrec a) (hb : Primrec b) (ht : Primrec t) (hv : Primrec v) : Primrec fun x => marked (f x) (a x) (b x) (t x) (v x) := Primrec.and.comp (Primrec.and.comp (goodRec hf ha hb ht) (PrimrecPred.or (memRec (Primrec.pair ha hb) (marksRec hf)).primrecPred (memRec (Primrec.pair hb ha) (marksRec hf)).primrecPred).decide) (matchedRec hf ha hb ht hv) theorem orderRec {f : A → Env} {p : A → List Event} (hf : Primrec f) (hp : Primrec p) : Primrec fun a => order (f a) (p a) := by apply Primrec.and.comp _ (seesRec (wordRec hf) hp) apply P455FramePrim.allB hp exact (PrimrecPred.not (Primrec.eq.comp (Primrec.snd.comp Primrec.snd) (Primrec.nat_sub.comp ((limRec hf).comp Primrec.fst) (.const 2)))).decide.to₂ theorem separateRec {f : A → Env} {a b : A → Nat} (hf : Primrec f) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => separate (f x) (a x) (b x) := Primrec.not.comp (P455WriterBlocks.sameRec (limRec hf) (wordRec hf) ha hb) theorem earlyBeforeRec {f : A → Env} {xs ys : A → W} (hf : Primrec f) (hx : Primrec xs) (hy : Primrec ys) : Primrec fun a => earlyBefore (f a) (xs a) (ys a) := by apply P455FramePrim.allB (choicesRec hx hy) apply Primrec₂.mk exact orderRec (hf.comp Primrec.fst) (Primrec.list_cons.comp (Primrec.pair (Primrec.fst.comp Primrec.snd) (.const 2)) (Primrec.list_cons.comp (Primrec.pair (Primrec.snd.comp Primrec.snd) (.const 0)) (.const []))) theorem earlyDisjointRec {f : A → Env} {xs ys : A → W} (hf : Primrec f) (hx : Primrec xs) (hy : Primrec ys) : Primrec fun a => earlyDisjoint (f a) (xs a) (ys a) := Primrec.or.comp (earlyBeforeRec hf hx hy) (earlyBeforeRec hf hy hx) end P455WriterQueryLeaves end /- Begin Problem455WriterStructuralRec (from finite-semigroup-identity-bases). -/ section namespace P455WriterStructural open P455WriterTiles P455WriterProfiles P455WriterObservations open Problem455.Slots variable {A : Type} [Primcodable A] theorem recordRec {r : A → Nat} {ts : A → Tags} {w : A → W} {a b : A → Nat} (hr : Primrec r) (ht : Primrec ts) (hw : Primrec w) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => recordB (r x) (ts x) (w x) (a x) (b x) := by apply Primrec.and.comp (PrimrecPred.not (Primrec.eq.comp ha hb)).decide apply P455GraphPrim.anyB (choicesRec ht (.const [false,true])) apply Primrec₂.mk have t := Primrec.fst.comp (Primrec.snd (α := A) (β := List Bool × Bool)) have v := Primrec.snd.comp (Primrec.snd (α := A) (β := List Bool × Bool)) have k := Primrec.list_cons.comp ha (Primrec.list_cons.comp hb (.const [])) exact (PrimrecPred.and (Primrec.eq.comp (Primrec.nat_add.comp (Primrec.list_length.comp t) (.const 16)) (hr.comp Primrec.fst)) (Primrec.eq.comp ((selectRec k hw).comp Primrec.fst) (profileRec (ha.comp Primrec.fst) (hb.comp Primrec.fst) t v))).decide theorem edgeRec {r : A → Nat} {ts : A → Tags} {w : A → W} {a b : A → Nat} (hr : Primrec r) (ht : Primrec ts) (hw : Primrec w) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => edgeB (r x) (ts x) (w x) (a x) (b x) := Primrec.or.comp (recordRec hr ht hw ha hb) (recordRec hr ht hw hb ha) theorem widthRec {k : A → Nat} {w : A → W} (hk : Primrec k) (hw : Primrec w) : Primrec fun x => widthB (k x) (w x) := by apply P455GraphPrim.anyB (P455GraphPrim.wordsUpTo.comp hw hk) apply Primrec₂.mk apply P455FramePrim.allB (hw.comp Primrec.fst) exact (P455CataloguePrim.mem'.comp Primrec.snd (Primrec.snd.comp Primrec.fst)).decide.to₂ theorem overlapRec {r : A → Nat} {ts : A → Tags} {w : A → W} (hr : Primrec r) (ht : Primrec ts) (hw : Primrec w) : Primrec fun x => overlapB (r x) (ts x) (w x) := by apply P455GraphPrim.anyB (choicesRec hw (choicesRec hw hw)) apply Primrec₂.mk have base := Primrec.fst (α := A) (β := Nat × Nat × Nat) have args := Primrec.snd (α := A) (β := Nat × Nat × Nat) have a := Primrec.fst.comp args have b := Primrec.fst.comp (Primrec.snd.comp args) have c := Primrec.snd.comp (Primrec.snd.comp args) have ab := PrimrecPred.not (Primrec.eq.comp a b) have ac := PrimrecPred.not (Primrec.eq.comp a c) have bc := PrimrecPred.not (Primrec.eq.comp b c) exact Primrec.and.comp (Primrec.and.comp (PrimrecPred.and ab (PrimrecPred.and ac bc)).decide (edgeRec (hr.comp base) (ht.comp base) (hw.comp base) a b)) (edgeRec (hr.comp base) (ht.comp base) (hw.comp base) a c) theorem intrusionRec {r : A → Nat} {ts : A → Tags} {w : A → W} (hr : Primrec r) (ht : Primrec ts) (hw : Primrec w) : Primrec fun x => intrusionB (r x) (ts x) (w x) := by apply P455GraphPrim.anyB (choicesRec hw (choicesRec hw (eventsRec.comp hw))) apply Primrec₂.mk have base := Primrec.fst (α := A) (β := Nat × Nat × Event) have args := Primrec.snd (α := A) (β := Nat × Nat × Event) have a := Primrec.fst.comp args have b := Primrec.fst.comp (Primrec.snd.comp args) have e := Primrec.snd.comp (Primrec.snd.comp args) have z := Primrec.fst.comp e have ab := PrimrecPred.not (Primrec.eq.comp a b) have za := PrimrecPred.not (Primrec.eq.comp z a) have zb := PrimrecPred.not (Primrec.eq.comp z b) have pattern := Primrec.list_cons.comp (Primrec.pair a (.const 0)) (Primrec.list_cons.comp e (Primrec.list_cons.comp (Primrec.pair b (.const 2)) (.const []))) exact Primrec.and.comp (Primrec.and.comp (PrimrecPred.and ab (PrimrecPred.and za zb)).decide (recordRec (hr.comp base) (ht.comp base) (hw.comp base) a b)) (seesRec (hw.comp base) pattern) theorem compressedRec {r : A → Nat} {w : A → W} (hr : Primrec r) (hw : Primrec w) : Primrec fun x => compressedB (r x) (w x) := by apply P455FramePrim.allB (choicesRec hw hw) apply Primrec₂.mk exact (PrimrecPred.not (Primrec.eq.comp (bigramRec (hw.comp Primrec.fst) (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp Primrec.snd)) (hr.comp Primrec.fst))).decide end P455WriterStructural end /- Begin Problem455FoldMachine (from finite-semigroup-identity-bases). -/ section namespace P455FoldMachine open Turing P455MachineLocal P455MachineTable P455MachineCleanup P455FoldWorld abbrev Sym (Γ : Type) := Option (Γ×Γ) abbrev Ctrl (Γ Q : Type) := Q×Bool×(Γ×Γ) abbrev Table (Γ Q : Type) := Q → Γ → Option (Q×TM0.Stmt Γ) def emit (s : Ctrl Γ Q) (a : Sym Γ) (z : Q) (i : TM0.Stmt Γ) : Ins (Sym Γ) (Ctrl Γ Q) := match i with | .move d => let m := motion s.2.1 a.isNone d ⟨(z,m.1,s.2.2),a,m.2⟩ | .write b => let h := if a.isNone then put s.2.1 s.2.2 b else s.2.2 ⟨(z,s.2.1,h),a.map (fun v => put s.2.1 v b),.stay⟩ def table (M : Table Γ Q) (s : Ctrl Γ Q) (a : Sym Γ) := (M s.1 (choose s.2.1 (a.getD s.2.2))).map (fun (z,i) => emit s a z i) theorem mark (s : Ctrl Γ Q) (a : Sym Γ) (z i) : (emit s a z i).symbol=none ↔ a=none := by cases i <;> cases a <;> simp [emit] theorem safe (s : Ctrl Γ Q) (z i) : (emit s none z i).dir≠.left := by cases s with | mk q p => obtain ⟨b,h⟩ := p cases i with | write => exact Direction.noConfusion | move d => cases d <;> cases b <;> exact Direction.noConfusion variable [Inhabited Γ] variable (aCode : Sym Γ ≃ Fin g) (sCode : Ctrl Γ Q ≃ Fin r) def number (i : Ins (Sym Γ) (Ctrl Γ Q)) : Ins (Fin g) (Fin r) := ⟨sCode i.state,aCode i.symbol,i.dir⟩ def machine (M : Table Γ Q) (start : Q) (header : Γ×Γ) : Ordinary g r where marker := aCode none blank := aCode (some (default,default)) blank_ne := by intro h have hh : (some (default,default) : Sym Γ) = none := aCode.injective h cases hh start := sCode (start,false,header) delta z a := (table M (sCode.symm z) (aCode.symm a)).map (number aCode sCode) keeps := by intro z a i e rcases Option.map_eq_some_iff.mp e with ⟨j,h,rfl⟩ rcases Option.map_eq_some_iff.mp h with ⟨⟨u,cmd⟩,_,rfl⟩ change aCode _=aCode none ↔ a=aCode none rw [aCode.injective.eq_iff,mark,Equiv.symm_apply_eq] leftSafe := by intro z i e simp only [Equiv.symm_apply_apply] at e rcases Option.map_eq_some_iff.mp e with ⟨j,h,rfl⟩ rcases Option.map_eq_some_iff.mp h with ⟨⟨u,cmd⟩,_,rfl⟩ exact safe (sCode.symm z) u cmd def cell (f : Int→Γ) (p : Nat) : Sym Γ := if p=0 then none else some (packed f p) def control (w : World Γ Q) : Ctrl Γ Q := (w.state,w.side,packed w.store 0) def physical (w : World Γ Q) : Config g r := ⟨fun j => aCode (cell w.store j),w.radius,sCode (control w)⟩ omit [Inhabited Γ] in theorem scanned (w : World Γ Q) : choose w.side ((cell w.store w.radius).getD (packed w.store 0))=w.store (pos w) := by cases h : w.radius with | zero => simp [cell,choose_packed,pos,h] | succ p => simp [cell,choose_packed,pos,h] theorem translated (M : Table Γ Q) (start : Q) (hdr : Γ×Γ) (w : World Γ Q) : instruction (machine aCode sCode M start hdr) (physical aCode sCode w)= (M w.state (w.store (pos w))).map (fun (z,i) => number aCode sCode (emit (control w) (cell w.store w.radius) z i)) := by simp only [instruction,machine,physical,Equiv.symm_apply_apply,table,control,scanned,Option.map_map] rfl theorem act_step (M : Table Γ Q) (start : Q) (hdr : Γ×Γ) (w : World Γ Q) (z i) (e : M w.state (w.store (pos w))=some (z,i)) : once (machine aCode sCode M start hdr) (physical aCode sCode w)= physical aCode sCode (act w z i) := by rw [once,translated,e] have noneEq : (cell w.store w.radius).isNone=decide (w.radius=0) := by cases w.radius <;> simp [cell] cases i with | move d => simp [emit,number,physical,control,act,P455EffectiveMachine.write_same,noneEq] | write b => have pp : pos w=coord w.side w.radius := rfl have head : packed (Function.update w.store (pos w) b) 0= (if (cell w.store w.radius).isNone then put w.side (packed w.store 0) b else packed w.store 0) := by rw [pp,put_packed,noneEq] by_cases h : w.radius=0 <;> simp [h,eq_comm] have tp : writeAt (fun j=>aCode (cell w.store j)) w.radius (aCode ((cell w.store w.radius).map (fun v => put w.side v b))) = fun j => aCode (cell (Function.update w.store (pos w) b) j) := by funext j by_cases e : j=w.radius · subst j; by_cases h : w.radius=0 <;> simp [writeAt,cell,h,pp,put_packed] · by_cases h : j=0 <;> simp [writeAt,e,cell,h,pp,put_packed] omega change (⟨_,_,_⟩ : Config g r) = ⟨_,_,_⟩ simp only [emit,number,physical,control,act,dest,head] at * congr 1 end P455FoldMachine end /- Begin Problem455WriterSlotsTerminal (from finite-semigroup-identity-bases). -/ section namespace P455WriterSlots open P455Witness (Tag Holds Query Marking SlotDefect) open P455WriterQueryLeaves P455WriterObservations P455WriterProfiles open Problem455.Slots def slot (e : Env) (o i a : Nat) := decide (slotStart i) && (events e.2.2.2).any (fun p => decide (sees e.2.2.2 [(o,i),(a,p.2),(o,i+1)])) def different (e : Env) : W → Bool | [] => true | a::t => t.all (separate e a) && different e t def holes (e : Env) (o i : Nat) (xs : W) := decide (xs.length=5) && different e (o::xs) && xs.all (fun a => decide (e.2.2.2.count a=e.1) && slot e o i a) def terminal (e : Env) (o i : Nat) (defect : SlotDefect) : Bool := match defect with | .deficient a => slot e o i a && decide (e.2.2.2.count a < e.1) | .overflow xs => holes e o i xs variable {e : Env} {r : Nat} {allow : Tag → Prop} {mark : Marking} {w : W} theorem slot_ok (h : ModelsEnv e r allow mark w) (o i a : Nat) : slot e o i a=true ↔ Holds r allow mark w (.slot o i a) := by simp only [slot,Bool.and_eq_true,decide_eq_true_eq,List.any_eq_true,h.word,Holds,occupies] apply and_congr_right intro _ constructor · rintro ⟨p,_,s⟩; exact ⟨p.2,s⟩ · rintro ⟨j,s⟩; exact ⟨(a,j),s.subset (by simp),s⟩ theorem different_ok (h : ModelsEnv e r allow mark w) (xs : W) : different e xs=true ↔ Holds r allow mark w (P455Witness.differentBlocks xs) := by induction xs with | nil => simp [different,P455Witness.differentBlocks,Holds] | cons a xs ih => simp [different,P455Witness.differentBlocks,Holds,P455PortReflection.holds_all,List.all_eq_true,ih,separate_ok h] theorem terminal_ok (h : ModelsEnv e r allow mark w) (o i d) : terminal e o i d=true ↔ Holds r allow mark w (P455Witness.terminalSlot r o i d) := by cases d with | deficient a => simp only [terminal,Bool.and_eq_true,slot_ok h,decide_eq_true_eq,h.word,h.lim,P455Witness.terminalSlot,Holds] | overflow xs => simp [terminal,holes,Bool.and_eq_true,slot_ok h,decide_eq_true_eq,h.word,h.lim,different_ok h,List.all_eq_true, P455Witness.terminalSlot,P455PortReflection.holds_all,Holds,and_assoc] variable {A : Type} [Primcodable A] theorem slotRec {e : A → Env} {o i a : A → Nat} (he : Primrec e) (ho : Primrec o) (hi : Primrec i) (ha : Primrec a) : Primrec fun x => slot (e x) (o x) (i x) (a x) := by have fixed : Primrec fun x => decide (slotStart (i x)) := by have hit := memRec hi (Primrec.const [0,1,3,5,7,9,11]) apply Primrec.of_eq hit intro x apply Bool.eq_iff_iff.mpr simp [slotStart] apply Primrec.and.comp fixed apply P455GraphPrim.anyB (eventsRec.comp (wordRec he)) apply Primrec₂.mk let cons := @Primrec.list_cons Event _ have o' := ho.comp (Primrec.fst (β := Event)) have i' := hi.comp (Primrec.fst (β := Event)) exact seesRec ((wordRec he).comp Primrec.fst) (cons.comp (o'.pair i') (cons.comp (Primrec.pair (ha.comp Primrec.fst) (Primrec.snd.comp Primrec.snd)) (cons.comp (o'.pair (Primrec.succ.comp i')) (.const [])))) theorem differentRec {e : A → Env} {l : A → W} (he : Primrec e) (hl : Primrec l) : Primrec fun x => different (e x) (l x) := by let h (x : A) (p : Nat×W×Bool) := p.2.1.all (separate (e x) p.1) && p.2.2 have hh : Primrec₂ h := by apply Primrec₂.mk apply Primrec.and.comp _ (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) apply P455FramePrim.allB (Primrec.fst.comp (Primrec.snd.comp Primrec.snd)) exact (separateRec ((he.comp Primrec.fst).comp Primrec.fst) ((Primrec.fst.comp Primrec.snd).comp Primrec.fst) Primrec.snd).to₂ apply (Primrec.list_rec hl (.const true) hh).of_eq intro x induction l x with | nil => rfl | cons a xs ih => exact congrArg (fun b => h x (a,xs,b)) ih theorem holesRec {e : A → Env} {o i : A → Nat} {xs : A → W} (he : Primrec e) (ho : Primrec o) (hi : Primrec i) (hl : Primrec xs) : Primrec fun x => holes (e x) (o x) (i x) (xs x) := by apply Primrec.and.comp (Primrec.and.comp (Primrec.eq.comp (Primrec.list_length.comp hl) (.const 5)).decide (differentRec he (Primrec.list_cons.comp ho hl))) apply P455FramePrim.allB hl exact (Primrec.and.comp (Primrec.eq.comp (P455CataloguePrim.count'.comp ((wordRec he).comp Primrec.fst) Primrec.snd) ((limRec he).comp Primrec.fst)).decide (slotRec (he.comp Primrec.fst) (ho.comp Primrec.fst) (hi.comp Primrec.fst) Primrec.snd)).to₂ theorem terminalRec {e : A → Env} {o i : A → Nat} {d : A → SlotDefect} (he : Primrec e) (ho : Primrec o) (hi : Primrec i) (hd : Primrec d) : Primrec fun x => terminal (e x) (o x) (i x) (d x) := by let a (x : A) (z : Nat) := slot (e x) (o x) (i x) z && decide ((e x).2.2.2.count z < (e x).1) have ha : Primrec₂ a := Primrec.and.comp (slotRec (he.comp Primrec.fst) (ho.comp Primrec.fst) (hi.comp Primrec.fst) Primrec.snd) (Primrec.nat_lt.comp (P455CataloguePrim.count'.comp ((wordRec he).comp Primrec.fst) Primrec.snd) ((limRec he).comp Primrec.fst)).decide let b (x : A) (xs : W) := holes (e x) (o x) (i x) xs have hb : Primrec₂ b := holesRec (he.comp Primrec.fst) (ho.comp Primrec.fst) (hi.comp Primrec.fst) Primrec.snd apply (Primrec.sumCasesOn (defectCodeRec.comp hd) ha hb).of_eq intro x cases d x <;> rfl end P455WriterSlots end /- Begin Problem455WriterSlotContact (from finite-semigroup-identity-bases). -/ section namespace P455WriterSlots open P455Witness (Tag Holds Marking ContactChoice) open P455WriterQueryLeaves P455WriterProfiles Problem455.Slots def portTest (e : Env) (a b : Nat) (p : Fin 5) (rev : Bool) := let i := 3+2*p.val let x := if rev then b else a let y := if rev then a else b decide (a≠b ∧ e.2.2.2.count a=e.1 ∧ e.2.2.2.count b=e.1) && earlyDisjoint e [a] [b] && order e [(x,i),(y,i),(x,i+1),(y,i+1)] def contact (e : Env) (a b : Nat) : ContactChoice → Bool | .record t v => if v then record e b a t else record e a b t | .port p v => portTest e a b p v theorem contact_ok {e : Env} {r : Nat} {allow : Tag → Prop} {mark : Marking} {w : W} (h : ModelsEnv e r allow mark w) (a b c) : contact e a b c=true ↔ Holds r allow mark w (P455Witness.contact r a b c) := by cases c with | record t v => cases v <;> simp [contact,P455Witness.contact,record_ok h] | port p v => simp [contact,portTest,P455Witness.contact,Bool.and_eq_true,earlyDisjoint_ok h,order_ok h, h.lim,h.word,P455Witness.allQ,Holds,and_assoc] variable {A : Type} [Primcodable A] theorem portRec {e : A → Env} {a b : A → Nat} {p : A → Fin 5} {v : A → Bool} (he : Primrec e) (ha : Primrec a) (hb : Primrec b) (hp : Primrec p) (hv : Primrec v) : Primrec fun x => portTest (e x) (a x) (b x) (p x) (v x) := by have i := Primrec.nat_add.comp (.const 3) (Primrec.nat_mul.comp (.const 2) (Primrec.fin_val.comp hp)) have cond := Primrec.eq.comp hv (.const true) have x := Primrec.ite cond hb ha have y := Primrec.ite cond ha hb let cons := @Primrec.list_cons Event _ have pat := cons.comp (x.pair i) (cons.comp (y.pair i) (cons.comp (x.pair (Primrec.succ.comp i)) (cons.comp (y.pair (Primrec.succ.comp i)) (.const [])))) exact Primrec.and.comp (Primrec.and.comp (PrimrecPred.and (PrimrecPred.not (Primrec.eq.comp ha hb)) (PrimrecPred.and (Primrec.eq.comp (P455CataloguePrim.count'.comp (wordRec he) ha) (limRec he)) (Primrec.eq.comp (P455CataloguePrim.count'.comp (wordRec he) hb) (limRec he)))).decide (earlyDisjointRec he (Primrec.list_cons.comp ha (.const [])) (Primrec.list_cons.comp hb (.const [])))) (orderRec he pat) theorem contactRec {e : A → Env} {a b : A → Nat} {c : A → ContactChoice} (he : Primrec e) (ha : Primrec a) (hb : Primrec b) (hc : Primrec c) : Primrec fun x => contact (e x) (a x) (b x) (c x) := by let f (x : A) (p : Tag × Bool) := if p.2 then record (e x) (b x) (a x) p.1 else record (e x) (a x) (b x) p.1 have hf : Primrec₂ f := Primrec.ite (Primrec.eq.comp (Primrec.snd.comp Primrec.snd) (.const true)) (recordRec (he.comp Primrec.fst) (hb.comp Primrec.fst) (ha.comp Primrec.fst) (Primrec.fst.comp Primrec.snd)) (recordRec (he.comp Primrec.fst) (ha.comp Primrec.fst) (hb.comp Primrec.fst) (Primrec.fst.comp Primrec.snd)) let g (x : A) (p : Fin 5 × Bool) := portTest (e x) (a x) (b x) p.1 p.2 have hg : Primrec₂ g := portRec (he.comp Primrec.fst) (ha.comp Primrec.fst) (hb.comp Primrec.fst) (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp Primrec.snd) apply (Primrec.sumCasesOn (contactCodeRec.comp hc) hf hg).of_eq intro x cases c x <;> rfl end P455WriterSlots end /- Begin Problem455WriterEdgePorts (from finite-semigroup-identity-bases). -/ section set_option maxHeartbeats 25000 namespace P455WriterEdge open P455Witness P455PaddedTiles P455WriterQueryLeaves abbrev roles (a : Node) := [a.owner,a.mate] def order2 (e : Env) (a i b j : Nat) := order e [(a,i),(b,j)] def nodeRecord (e : Env) (a : Node) := record e a.owner a.mate a.tag def nodeMarked (e : Env) (a : Node) (bit : Bool) := marked e a.owner a.mate a.tag bit def port (e : Env) (p : Nat) (a b : Node) := let i := 3+2*p nodeRecord e a && (nodeRecord e b && (P455WriterQueryLeaves.earlyDisjoint e (roles a) (roles b) && order e [(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)])) theorem port_ok (h : ModelsEnv e r allow mark w) (p a b) : port e p a b=true ↔ Holds r allow mark w (orientedPort p a b) := by simp only [port,nodeRecord,Bool.and_eq_true,record_ok h,earlyDisjoint_ok h,order_ok h] change (_ ∧ (_ ∧ (_ ∧ _))) ↔ (_ ∧ (_ ∧ (_ ∧ (_ ∧ True)))) exact Iff.intro (fun ⟨a,b,c,d⟩ => ⟨a,b,c,d,trivial⟩) (fun ⟨a,b,c,d,_⟩=>⟨a,b,c,d⟩) def rightB (e : Env) (n : Nat) (a b : Node) := P455WriterTiles.horizontal n a.tag b.tag && (port e (if (system n).oddColumn a.tag then 1 else 0) a b && order2 e a.owner (13+a.tag.length) b.owner (13+a.tag.length)) def downB (e : Env) (n : Nat) (a b : Node) := P455WriterTiles.vertical n a.tag b.tag && port e (if (system n).oddRow a.tag then 3 else 2) a b def neighborB (e : Env) (n : Nat) (a b : Node) : Dir → Bool | .right => rightB e n a b | .left => rightB e n b a | .down => downB e n a b | .up => downB e n b a theorem right_ok (h : ModelsEnv e r allow mark w) (n a b) : rightB e n a b=true ↔ Holds r allow mark w (rightward (system n) a b) := by simp only [rightB,order2,Bool.and_eq_true,P455WriterTiles.horizontal_correct,port_ok h,order_ok h] exact Iff.intro (fun ⟨a,b,c⟩=>⟨a,b,c,trivial⟩) (fun ⟨a,b,c,_⟩=>⟨a,b,c⟩) theorem down_ok (h : ModelsEnv e r allow mark w) (n a b) : downB e n a b=true ↔ Holds r allow mark w (downward (system n) a b) := by simp only [downB,Bool.and_eq_true,P455WriterTiles.vertical_correct,port_ok h]; rfl theorem neighbor_ok (h : ModelsEnv e r allow mark w) (n a b d) : neighborB e n a b d=true ↔ Holds r allow mark w (neighbor (system n) a b d) := by cases d with | right => exact right_ok h n a b | left => exact right_ok h n b a | down => exact down_ok h n a b | up => exact down_ok h n b a def role (b : Bool) (a : Node) := if b then a.mate else a.owner def funcB (e : Env) (n : Nat) (f : FunctionalityCertificate) := nodeMarked e f.anchor f.bit && (neighborB e n f.anchor f.b f.dir && (neighborB e n f.anchor f.c f.dir && separate e (role f.distinguishMate f.b) (role f.distinguishMate f.c))) theorem func_ok (h : ModelsEnv e r allow mark w) (n f) : funcB e n f=true ↔ Holds r allow mark w (f.query (system n)) := by simp only [funcB,nodeMarked,Bool.and_eq_true,marked_ok h,neighbor_ok h,separate_ok h] exact Iff.intro (fun ⟨a,b,c,d⟩=>⟨a,b,c,d,trivial⟩) (fun ⟨a,b,c,d,_⟩=>⟨a,b,c,d⟩) def funcAccept (e : Env) (n a b : Nat) := (P455Enum.functionalities e.2.2.2 e.2.1).any fun f => decide (f.anchor.owner=a ∧ f.anchor.mate=b) && funcB e n f theorem funcAccept_ok (M : MachineTable n) (h : ModelsEnv e r (allowed M) mark w) (tags : e.2.1=P455Enum.tags M) (a b) : funcAccept e n a b=true ↔ ∃ f : FunctionalityCertificate, f.anchor.owner=a ∧ f.anchor.mate=b ∧ Holds r (allowed M) mark w (f.query (system n)) := by simp only [funcAccept,List.any_eq_true,Bool.and_eq_true,decide_eq_true_eq,func_ok h,h.word,tags] constructor · rintro ⟨f,_,⟨ha,hb⟩,hf⟩; exact ⟨f,ha,hb,hf⟩ · rintro ⟨f,ha,hb,hf⟩; exact ⟨f,P455Enum.func_mem M f hf,⟨ha,hb⟩,hf⟩ end P455WriterEdge end /- Begin Problem455WriterStructural (from finite-semigroup-identity-bases). -/ section namespace P455WriterStructural open P455WriterTiles P455WriterProfiles P455PaddedTiles P455StructuralProduct def wordAt (r i : Nat) := (templates r)[i]?.getD [] def test (r : Nat) (ts : Tags) (w : W) := P455EffectiveQMove.capB r w && compressedB r w && ((widthB 4 w && overlapB r ts w) || (widthB 3 w && intrusionB r ts w)) theorem test_correct {r : Nat} (pos : 0 test r ts (wordAt r i) theorem getWord (r : Nat) (i : Fin (templates r).length) : wordAt r i.val=(templates r).get i := by simp [wordAt,i.isLt] private theorem attachIndices {n : Nat} (xs : List (Fin n)) : xs.attach.map (fun x => x.val.val) = xs.map Fin.val := @List.attach_map_val (Fin n) Nat xs Fin.val theorem indices_correct {r : Nat} (pos : 0 (wordAt r i,none) theorem structural_correct {r : Nat} (pos : 0 test (r a) (ts a) (w a) := Primrec.and.comp (Primrec.and.comp (P455FrameProof.capCheck hr hw) (compressedRec hr hw)) (Primrec.or.comp (Primrec.and.comp (widthRec (.const 4) hw) (overlapRec hr ht hw)) (Primrec.and.comp (widthRec (.const 3) hw) (intrusionRec hr ht hw))) theorem structuralRec {r : A → Nat} {ts : A → Tags} (hr : Primrec r) (ht : Primrec ts) : Primrec fun a => structural (r a) (ts a) := by have ids := Primrec.list_range.comp (Primrec.list_length.comp (templatesRec.comp hr)) have w := wordAtRec.comp (hr.comp (Primrec.fst (β := Nat))) Primrec.snd have valid : Primrec₂ (fun a i => test (r a) (ts a) (wordAt (r a) i)) := testRec (hr.comp Primrec.fst) (ht.comp Primrec.fst) w have idx := P455GraphPrim.filter ids valid exact Primrec.list_map (P455CataloguePrim.distinct'.comp idx) (Primrec.pair w (.const none)).to₂ end P455WriterStructural end /- Begin Problem455FoldRun (from finite-semigroup-identity-bases). -/ section namespace P455FoldRun open Turing P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine open P455WriterSweep P455FoldWorld P455FoldMachine def Marked (flag : Γ → Bool) (w : World Γ Q) := ∀ p, flag (w.store p)=true ↔ p=0 theorem survives (flag : Γ→Bool) (M : Table Γ Q) (w : World Γ Q) (guard : ∀ q a z b, M q a=some (z,.write b) → flag b=flag a) {z i} (step : M w.state (w.store (pos w))=some (z,i)) (h : Marked flag w) : Marked flag (act w z i) := by cases i with | move d => exact h | write b => intro p change flag (Function.update w.store (pos w) b p)=true ↔ p=0 by_cases eq : p=pos w · subst p; simpa [guard _ _ _ _ step] using h (pos w) · simpa [Function.update_of_ne eq] using h p variable [Inhabited Γ] [Inhabited Q] variable (aCode : Sym Γ ≃ Fin g) (sCode : Ctrl Γ Q ≃ Fin r) theorem lift_reaches (M : TM0.Machine Γ Q) (header : Γ×Γ) (flag : Γ→Bool) (guard : ∀ q a z b, M q a=some (z,.write b) → flag b=flag a) {u v : TM0.Cfg Γ Q} (path : StateTransition.Reaches (TM0.step M) u v) (w₀ : World Γ Q) (d₀ : Describes w₀ u) (m₀ : Marked flag w₀) : ∃ w, Describes w v ∧ Marked flag w ∧ reach (machine aCode sCode M default header) (physical aCode sCode w₀) (physical aCode sCode w) := by induction path with | refl => exact ⟨_,d₀,m₀,0,rfl⟩ | @tail a b _ step ih => obtain ⟨w,d,m,h⟩ := ih obtain ⟨q,T⟩ := a rcases Option.map_eq_some_iff.mp step with ⟨⟨z,i⟩,e,rfl⟩ change M q T.head=some (z,i) at e have scan : T.head=w.store (pos w) := by simpa using d.2 0 have exec : M w.state (w.store (pos w))=some (z,i) := by rw [d.1,←scan]; exact e exact ⟨_,act_describes d z i,survives flag M w guard exec m, P455WriterSweep.trans h (single (act_step aCode sCode M default header w z i exec))⟩ end P455FoldRun end /- Begin Problem455FoldInput (from finite-semigroup-identity-bases). -/ section namespace P455FoldInput open Turing P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine open P455FoldWorld P455FoldMachine structure Wire (Γ : Type) [Inhabited Γ] where first : Γ second : Γ letter : Bool→Γ ink : ∀ b, letter b≠default distinct : letter false≠letter true flag : Γ→Bool flags : flag first=true ∧ flag second=false ∧ flag default=false ∧ ∀ b, flag (letter b)=false variable [Inhabited Γ] def stream (C : Wire Γ) (x : List Bool) := C.first::C.second::x.map C.letter def layout (C : Wire Γ) (x : List Bool) : Int→Γ | .negSucc _ => default | .ofNat 0 => C.first | .ofNat 1 => C.second | .ofNat (i+2) => (x[i]?).elim default C.letter theorem nth_stream (C : Wire Γ) (x : List Bool) (i : Int) : (Tape.mk₁ (stream C x)).nth i=layout C x i := by cases i with | negSucc n => change (ListBlank.mk ([] : List Γ)).nth n=default simp [ListBlank.nth_mk] | ofNat n => change (Tape.mk' _ (ListBlank.mk (stream C x))).nth (n : Int)=_ rw [Tape.mk'_nth_nat,ListBlank.nth_mk,List.getI_eq_iget_getElem?] cases n with | zero => rfl | succ n => cases n with | zero => rfl | succ n => simp only [stream,List.getElem?_cons_succ,List.getElem?_map,layout] cases x[n]? <;> rfl theorem marked (C : Wire Γ) (x : List Bool) (p : Int) : C.flag (layout C x p)=true ↔ p=0 := by obtain ⟨one,two,b,all⟩ := C.flags cases p with | negSucc n => simp [layout,b] | ofNat n => cases n with | zero => simp [layout,one] | succ n => cases n with | zero => simp [layout,two] | succ n => cases e : x[n]? <;> simp [layout,e,b,all] <;> omega def initWorld [Inhabited Q] (C : Wire Γ) (x : List Bool) : World Γ Q := ⟨layout C x,false,0,default⟩ theorem describes_init [Inhabited Q] (C : Wire Γ) (x : List Bool) : Describes (initWorld (Q:=Q) C x) (TM0.init (stream C x)) := by refine ⟨rfl,fun i => ?_⟩ simpa [TM0.init,initWorld,pos,coord] using nth_stream C x i variable [Inhabited Q] variable (aCode : Sym Γ ≃ Fin g) (sCode : Ctrl Γ Q ≃ Fin r) def inputAlpha (M : Table Γ Q) (C : Wire Γ) : Alphabet (machine aCode sCode M default (C.first,C.second)) where bit b := aCode (some (default,C.letter b)) away b eq := by have hh : (some (default,C.letter b) : Sym Γ) = none := aCode.injective eq cases hh ink b eq := C.ink b (congrArg Prod.snd (Option.some.inj (aCode.injective eq))) distinct eq := C.distinct (congrArg Prod.snd (Option.some.inj (aCode.injective eq))) theorem cell_layout (M : Table Γ Q) (C : Wire Γ) (x : List Bool) : (fun j => aCode (cell (layout C x) j))= inputTape _ (inputAlpha aCode sCode M C) x := by funext j; cases j with | zero => rfl | succ j => change aCode (some (packed (layout C x) (j+1)))=(x[j]?).elim (aCode (some (default,default))) (fun b => aCode (some (default,C.letter b))) have left : coord false (j+1)=Int.negSucc j := by simp [coord]; omega have right : coord true (j+1)=Int.ofNat (j+2) := by simp [coord]; omega simp only [packed,left,right,layout] cases x[j]? <;> rfl theorem initial (M : Table Γ Q) (C : Wire Γ) (x : List Bool) : physical aCode sCode (initWorld (Q:=Q) C x)= inputConfig _ (inputAlpha aCode sCode M C) x := by change (⟨_,0,sCode (default,false,packed (layout C x) 0)⟩ : Config g r)= ⟨_,0,sCode (default,false,(C.first,C.second))⟩ dsimp only [initWorld] rw [cell_layout aCode sCode M C x] rfl end P455FoldInput end /- Begin Problem455WriterSlots (from finite-semigroup-identity-bases). -/ section namespace P455WriterSlots open P455Witness (Tag Holds Marking ContactChoice SlotCertificate) open P455WriterQueryLeaves P455WriterProfiles P455WriterEdge abbrev Step := Nat × ContactChoice def visit (e : Env) (s : Nat×Bool) (b : Step) := (b.1, s.2 && contact e s.1 b.1 b.2) def walk (e : Env) (s : Nat×Bool) (bs : List Step) := bs.foldl (visit e) s def sat (e : Env) (s : SlotCertificate) := let start := if s.startAtMate then s.anchor.mate else s.anchor.owner let last := walk e (start,true) s.steps marked e s.anchor.owner s.anchor.mate s.anchor.tag s.bit && decide (s.steps.length≤6) && last.2 && terminal e last.1 s.terminalIndex s.defect variable {e : Env} {r : Nat} {allow : Tag → Prop} {mark : Marking} {w : W} theorem walk_ok (h : ModelsEnv e r allow mark w) (s : Nat × Bool) (bs : List Step) (i d) : ((walk e s bs).2=true ∧ terminal e (walk e s bs).1 i d=true) ↔ s.2=true ∧ Holds r allow mark w (P455Witness.route r s.1 bs (fun a => P455Witness.terminalSlot r a i d)) := by induction bs generalizing s with | nil => simp only [walk,List.foldl_nil,P455Witness.route,terminal_ok h] | cons b bs ih => change (_ ∧ _) ↔ s.2=true ∧ Holds r allow mark w (.both _ _) rw [show walk e s (b::bs) = walk e (visit e s b) bs by rfl,ih] simp only [visit,Holds,Bool.and_eq_true,contact_ok h,and_assoc] theorem sat_ok (h : ModelsEnv e r allow mark w) (s : SlotCertificate) : sat e s=true ↔ Holds r allow mark w (s.query r) := by simp only [sat,Bool.and_eq_true,and_assoc,walk_ok h,true_and,marked_ok h,decide_eq_true_eq, P455Witness.SlotCertificate.query,P455Witness.allQ,Holds,P455Witness.markedNode,and_true] variable {A : Type} [Primcodable A] theorem walkRec {e : A → Env} {s : A → Nat×Bool} {bs : A → List Step} (he : Primrec e) (hs : Primrec s) (hb : Primrec bs) : Primrec fun a => walk (e a) (s a) (bs a) := by let step (a : A) (p : (Nat×Bool)×Step) := visit (e a) p.1 p.2 apply Primrec.list_foldl (h:=step) hb hs apply Primrec₂.mk have p := Primrec.snd (α := A) (β := (Nat×Bool) × Step) have i := Primrec.fst.comp (Primrec.fst.comp p) have yes := Primrec.snd.comp (Primrec.fst.comp p) have j := Primrec.fst.comp (Primrec.snd.comp p) have c := Primrec.snd.comp (Primrec.snd.comp p) exact j.pair (Primrec.and.comp yes (contactRec (he.comp Primrec.fst) i j c)) theorem satRec {e : A → Env} {s : A → SlotCertificate} (he : Primrec e) (hs : Primrec s) : Primrec fun a => sat (e a) (s a) := by have z := slotCodeRec.comp hs have node := Primrec.fst.comp z have a := ownerRec.comp node have b := mateRec.comp node have tag := tagRec.comp node have tail1 := Primrec.snd.comp z have bit := Primrec.fst.comp tail1 have tail2 := Primrec.snd.comp tail1 have atMate := Primrec.fst.comp tail2 have tail3 := Primrec.snd.comp tail2 have steps := Primrec.fst.comp tail3 have tail4 := Primrec.snd.comp tail3 have i := Primrec.fst.comp tail4 have d := Primrec.snd.comp tail4 have start := Primrec.ite (Primrec.eq.comp atMate (.const true)) b a have last := walkRec he (start.pair (.const true)) steps exact Primrec.and.comp (Primrec.and.comp (Primrec.and.comp (markedRec he a b tag bit) (Primrec.nat_le.comp (Primrec.list_length.comp steps) (.const 6)).decide) (Primrec.snd.comp last)) (terminalRec he (Primrec.fst.comp last) i d) def slotAccept (e : Env) (a b : Nat) := (P455Enum.slots e.2.2.2 e.2.1).any fun s => decide (s.anchor.owner=a ∧ s.anchor.mate=b) && sat e s theorem slotAcceptRec {e : A → Env} {a b : A → Nat} (he : Primrec e) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => slotAccept (e x) (a x) (b x) := by apply P455GraphPrim.anyB (slotsRec (wordRec he) (tagsRec he)) apply Primrec₂.mk have s := Primrec.snd (α := A) (β := SlotCertificate) have node := Primrec.fst.comp (slotCodeRec.comp s) exact Primrec.and.comp (PrimrecPred.and (Primrec.eq.comp (ownerRec.comp node) (ha.comp Primrec.fst)) (Primrec.eq.comp (mateRec.comp node) (hb.comp Primrec.fst))).decide (satRec (he.comp Primrec.fst) s) theorem slotAccept_ok (M : P455PaddedTiles.MachineTable n) {e : Env} {r : Nat} {mark : Marking} {w : W} (h : ModelsEnv e r (P455PaddedTiles.allowed M) mark w) (ht : e.2.1=P455Enum.tags M) (a b) : slotAccept e a b=true ↔ ∃ s : SlotCertificate, s.anchor.owner=a ∧ s.anchor.mate=b ∧ Holds r (P455PaddedTiles.allowed M) mark w (s.query r) := by simp only [slotAccept,List.any_eq_true,Bool.and_eq_true,decide_eq_true_eq,sat_ok h,h.word,ht] constructor · rintro ⟨s,_,⟨ha,hb⟩,ok⟩; exact ⟨s,ha,hb,ok⟩ · rintro ⟨s,ha,hb,ok⟩; exact ⟨s,P455Enum.slot_mem M s ok,⟨ha,hb⟩,ok⟩ end P455WriterSlots end /- Begin Problem455WriterEdgeTests (from finite-semigroup-identity-bases). -/ section set_option maxHeartbeats 30000 namespace P455WriterEdge open P455Witness P455PaddedTiles P455WriterQueryLeaves def whenB (b p : Bool) := if b then p else true theorem when_ok {e : Env} {v : Bool} {z : Query} (b : Bool) (h : v=true ↔ Holds e.1 allow mark w z) : whenB b v=true ↔ Holds e.1 allow mark w (flagQ b z) := by cases b <;> simp [whenB,flagQ,Holds,h] def localB (env : Env) (n : Nat) (e : EdgeCertificate) := let a := e.a let ts := system n whenB (!ts.right a.tag) (rightB env n a e.right) && (whenB (!ts.left a.tag) (rightB env n e.left a) && (whenB (!ts.bottom a.tag) (downB env n a e.down) && (whenB (!ts.top a.tag) (downB env n e.up a) && whenB (!ts.right a.tag && !ts.bottom a.tag) (downB env n e.right e.diagonal && rightB env n e.down e.diagonal)))) theorem local_ok (h : ModelsEnv env r allow mark w) (n) (e : EdgeCertificate) : localB env n e=true ↔ Holds r allow mark w (localCert (system n) e) := by have flag {v : Bool} {z : Query} (b : Bool) (hv : v=true ↔ Holds r allow mark w z) : whenB b v=true ↔ Holds r allow mark w (flagQ b z) := by cases b <;> simp [whenB,flagQ,Holds,hv] have diag : (downB env n e.right e.diagonal && rightB env n e.down e.diagonal)=true ↔ Holds r allow mark w (.both (downward (system n) e.right e.diagonal) (rightward (system n) e.down e.diagonal)) := by simp only [Bool.and_eq_true,down_ok h,right_ok h]; rfl simp only [localB,Bool.and_eq_true,flag _ (right_ok h ..),flag _ (down_ok h ..),flag _ diag] simp only [localCert,allQ,Holds,and_true] def chosenB (env : Env) (n : Nat) (e : EdgeCertificate) := let a := e.a; let b := e.b; let ts := system n if endOfRow ts a && ts.bottom a.tag then (ts.top b.tag && ts.left b.tag && !ts.oddRow b.tag && !ts.oddColumn b.tag) && ((port env 4 a b || port env 4 b a) && order2 env b.owner 0 a.owner 0) else let next := if endOfRow ts a then e.down else if ts.oddRow a.tag then e.left else e.right decide (next=b) && order2 env a.owner 0 b.owner 0 theorem chosen_ok (h : ModelsEnv env r allow mark w) (n) (e : EdgeCertificate) : chosenB env n e=true ↔ Holds r allow mark w (chosenSuccessor (system n) e) := by dsimp only [chosenB,chosenSuccessor] split <;> simp only [allQ,Holds,Bool.and_eq_true,Bool.or_eq_true,port_ok h,order2,order_ok h, earlier,decide_eq_true_eq,and_true] def queryB (env : Env) (n : Nat) (e : EdgeCertificate) := nodeMarked env e.a true && (nodeMarked env e.b false && (localB env n e && chosenB env n e)) theorem query_ok (h : ModelsEnv env r allow mark w) (n) (e : EdgeCertificate) : queryB env n e=true ↔ Holds r allow mark w (e.query (system n)) := by simp only [queryB,Bool.and_eq_true,nodeMarked,marked_ok h,local_ok h,chosen_ok h] simp only [EdgeCertificate.query,allQ,Holds,markedNode,and_true] def sameNames (xs ys : List Nat) := xs.all (fun x => decide (x∈ys)) && ys.all (fun y => decide (y∈xs)) theorem same_ok (xs ys : List Nat) : sameNames xs ys=true ↔ ∀ x, x∈xs ↔ x∈ys := by simp only [sameNames,Bool.and_eq_true,List.all_eq_true,decide_eq_true_eq] exact ⟨fun ⟨f,g⟩ x => ⟨f x,g x⟩, fun h => ⟨fun x => (h x).1,fun y => (h y).2⟩⟩ def env (r : Nat) (ts : List (List Bool)) (w : List Nat) (k : Quad) : Env := (r,ts,[(k.1,k.2.1),(k.2.2.1,k.2.2.2)],w) def tests (r n : Nat) (ts : List (List Bool)) (w : List Nat) (k : Quad) := P455EffectiveQMove.capB r w && (P455Enum.certificates w ts).any fun e => decide (e.a.owner=k.1 ∧ e.a.mate=k.2.1 ∧ e.b.owner=k.2.2.1 ∧ e.b.mate=k.2.2.2) && (sameNames w (P455EdgeProjection.names (system n) e) && queryB (env r ts w k) n e) theorem tests_ok (M : MachineTable n) (hr : 0 P455Enum.mem_tags,fun _ _ => by rcases k with ⟨a,b,c,d⟩; simp [env,P455EdgeProduct.marks],rfl,hr⟩ simp only [tests,Bool.and_eq_true,P455EffectiveQMove.cap_iff,List.any_eq_true,decide_eq_true_eq, same_ok,query_ok h,ValidKey] constructor · rintro ⟨cap,e,_,⟨a,b,c,d⟩,ns,hq⟩; exact ⟨cap,e,a,b,c,d,ns,hq⟩ · rintro ⟨cap,e,a,b,c,d,ns,hq⟩ obtain ⟨z,za,zb,ne,zq,hz⟩ := P455CatalogueBounds.bounded_edge cap (P455Enum.tags M) (fun _ ht => P455Enum.mem_tags.mpr ht) e hq exact ⟨cap,z,P455Enum.bounded_mem z hz,⟨za ▸ a,za ▸ b,zb ▸ c,zb ▸ d⟩,ne ▸ ns,zq⟩ def edges (r n : Nat) (ts : List (List Bool)) := family r (tests r n ts) theorem edges_correct (M : MachineTable n) (hr : 0 order2 (e x) (a x) (i x) (b x) (j x) := orderRec he (Primrec.list_cons.comp (ha.pair hi) (Primrec.list_cons.comp (hb.pair hj) (.const []))) theorem nodeRecordRec {e : A→Env} {a : A→Node} (he : Primrec e) (ha : Primrec a) : Primrec fun x => nodeRecord (e x) (a x) := recordRec he (ownerRec.comp ha) (mateRec.comp ha) (tagRec.comp ha) theorem nodeMarkedRec {e : A→Env} {a : A→Node} {v : A→Bool} (he : Primrec e) (ha : Primrec a) (hv : Primrec v) : Primrec fun x => nodeMarked (e x) (a x) (v x) := markedRec he (ownerRec.comp ha) (mateRec.comp ha) (tagRec.comp ha) hv theorem portRec {e : A→Env} {p : A→Nat} {a b : A→Node} (he : Primrec e) (hp : Primrec p) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => port (e x) (p x) (a x) (b x) := by have i := Primrec.nat_add.comp (.const 3) (Primrec.nat_mul.comp (.const 2) hp) have j := Primrec.nat_add.comp i (.const 1) have u := ownerRec.comp ha; have v := mateRec.comp ha; have y := ownerRec.comp hb; have z := mateRec.comp hb let cons := @Primrec.list_cons (Nat × Nat) _ have upper := cons.comp (u.pair j) (cons.comp (v.pair j) (cons.comp (y.pair j) (cons.comp (z.pair j) (.const [])))) have pat := cons.comp (u.pair i) (cons.comp (v.pair i) (cons.comp (y.pair i) (cons.comp (z.pair i) upper))) exact Primrec.and.comp (nodeRecordRec he ha) (Primrec.and.comp (nodeRecordRec he hb) (Primrec.and.comp (earlyDisjointRec he (rolesRec.comp ha) (rolesRec.comp hb)) (orderRec he pat))) theorem flagRec (i : Nat) {a : A→Node} (ha : Primrec a) : Primrec fun x => (a x).tag[i]?.getD false := Primrec.option_getD.comp (Primrec.list_getElem?.comp (tagRec.comp ha) (.const i)) (.const false) theorem rightRec {e : A→Env} {n : A→Nat} {a b : A→Node} (he : Primrec e) (hn : Primrec n) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => rightB (e x) (n x) (a x) (b x) := by have t := tagRec.comp ha have i := Primrec.nat_add.comp (.const 13) (Primrec.list_length.comp t) exact Primrec.and.comp (P455WriterTiles.horizontalRec hn t (tagRec.comp hb)) (Primrec.and.comp (portRec he (Primrec.ite (Primrec.eq.comp (flagRec 5 ha) (.const true)) (.const 1) (.const 0)) ha hb) (order2Rec he (ownerRec.comp ha) i (ownerRec.comp hb) i)) theorem downRec {e : A→Env} {n : A→Nat} {a b : A→Node} (he : Primrec e) (hn : Primrec n) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => downB (e x) (n x) (a x) (b x) := Primrec.and.comp (P455WriterTiles.verticalRec hn (tagRec.comp ha) (tagRec.comp hb)) (portRec he (Primrec.ite (Primrec.eq.comp (flagRec 4 ha) (.const true)) (.const 3) (.const 2)) ha hb) def selectDir (d : Dir) (rt lt dn up : Bool) := bif (dirCode d).1 then (bif (dirCode d).2 then up else dn) else (bif (dirCode d).2 then lt else rt) theorem chosenDir (e : Env) (n : Nat) (a b : Node) (d : Dir) : selectDir d (rightB e n a b) (rightB e n b a) (downB e n a b) (downB e n b a)=neighborB e n a b d := by cases d <;> simp only [selectDir,dirCode,Equiv.coe_fn_mk,cond_true,cond_false,neighborB] theorem neighborRec {e : A→Env} {n : A→Nat} {a b : A→Node} {d : A→Dir} (he : Primrec e) (hn : Primrec n) (ha : Primrec a) (hb : Primrec b) (hd : Primrec d) : Primrec fun x => neighborB (e x) (n x) (a x) (b x) (d x) := by have pair := dirCodeRec.comp hd have test : Primrec (fun x => selectDir (d x) (rightB (e x) (n x) (a x) (b x)) (rightB (e x) (n x) (b x) (a x)) (downB (e x) (n x) (a x) (b x)) (downB (e x) (n x) (b x) (a x))) := Primrec.cond (Primrec.fst.comp pair) (Primrec.cond (Primrec.snd.comp pair) (downRec he hn hb ha) (downRec he hn ha hb)) (Primrec.cond (Primrec.snd.comp pair) (rightRec he hn hb ha) (rightRec he hn ha hb)) exact test.of_eq (fun x => chosenDir (e x) (n x) (a x) (b x) (d x)) theorem roleRec {b : A→Bool} {a : A→Node} (hb : Primrec b) (ha : Primrec a) : Primrec fun x => role (b x) (a x) := Primrec.ite (Primrec.eq.comp hb (.const true)) (mateRec.comp ha) (ownerRec.comp ha) theorem funcRec {e : A→Env} {n : A→Nat} {f : A→FunctionalityCertificate} (he : Primrec e) (hn : Primrec n) (hf : Primrec f) : Primrec fun x => funcB (e x) (n x) (f x) := by have a := funcAnchorRec.comp hf; have b := funcBRec.comp hf; have c := funcCRec.comp hf have d := funcDirRec.comp hf; have v := funcDistinguishMateRec.comp hf exact Primrec.and.comp (nodeMarkedRec he a (funcBitRec.comp hf)) (Primrec.and.comp (neighborRec he hn a b d) (Primrec.and.comp (neighborRec he hn a c d) (separateRec he (roleRec v b) (roleRec v c)))) theorem funcAcceptRec {e : A→Env} {n a b : A→Nat} (he : Primrec e) (hn : Primrec n) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => funcAccept (e x) (n x) (a x) (b x) := by have F := Primrec.snd (α:=A) (β:=FunctionalityCertificate) have anc := funcAnchorRec.comp F exact P455GraphPrim.anyB (functionalitiesRec (wordRec he) (tagsRec he)) (Primrec.and.comp ((Primrec.eq.comp (ownerRec.comp anc) (ha.comp Primrec.fst)).and (Primrec.eq.comp (mateRec.comp anc) (hb.comp Primrec.fst))).decide (funcRec (he.comp Primrec.fst) (hn.comp Primrec.fst) F)).to₂ end P455WriterEdge end /- Begin Problem455FoldDelivery (from finite-semigroup-identity-bases). -/ section namespace P455FoldDelivery open Turing P455MachineLocal P455MachineTable P455MachineCleanup P455EffectiveMachine P455EffectiveChain open P455FoldWorld P455FoldMachine P455FoldRun P455FoldInput /-- A finite supported bilateral writer whose bottom flag is preserved becomes an ordinary finite one-sided writer with the exact physical bit-list convention. -/ theorem exact_delivery {Γ Q : Type} [Inhabited Γ] [Inhabited Q] [Fintype Γ] [Fintype Q] (M : TM0.Machine Γ Q) (C : Wire Γ) (guard : ∀ q a z b, M q a=some (z,.write b) → C.flag b=C.flag a) (f : List Bool → List Bool) (run : ∀ x, ∃ q, (⟨q,Tape.mk₁ (stream C (f x))⟩ : TM0.Cfg Γ Q) ∈ StateTransition.eval (TM0.step M) (TM0.init (stream C x))) : ∃ (g r : Nat) (W : Ordinary g r) (A : Alphabet W), ∀ x, Delivers W A x W A (f x) := by classical let ac := Fintype.equivFin (Sym Γ) let sc := Fintype.equivFin (Ctrl Γ Q) let W := machine ac sc M default (C.first,C.second) let A := inputAlpha ac sc M C refine ⟨_,_,W,A,?_⟩ intro x obtain ⟨q,last⟩ := run x obtain ⟨steps,halt⟩ := StateTransition.mem_eval.mp last obtain ⟨w,descr,mark,t,arrive⟩ := lift_reaches ac sc M (C.first,C.second) C.flag guard steps (initWorld C x) (describes_init C x) (marked C x) rw [initial ac sc M C] at arrive have eq (i : Int) : layout C (f x) i=w.store (pos w+i) := (nth_stream C (f x) i).symm.trans (descr.2 i) have head : pos w=0 := by apply (mark (pos w)).mp have he : C.first=w.store (pos w) := by simpa [layout] using eq 0 rw [←he]; exact C.flags.1 have rad : w.radius=0 := by unfold pos at head cases e : w.side <;> simp [e,coord] at head <;> omega have storeEq : w.store=layout C (f x) := by funext i; simpa [head] using (eq i).symm have hM : M q (Tape.mk₁ (stream C (f x))).head=none := by change (M q _).map _=none at halt exact Option.map_eq_none_iff.mp halt have scan := descr.2 0 simp only [Tape.nth_zero,Int.add_zero] at scan have ended : M w.state (w.store (pos w))=none := by rw [descr.1,←scan]; exact hM refine ⟨t,?_⟩ change follow W (inputConfig W A x) t=physical ac sc w at arrive dsimp only rw [arrive] refine ⟨?_,rad,?_⟩ · change instruction (machine ac sc M default (C.first,C.second)) (physical ac sc w)=none rw [translated,ended]; rfl · change (fun j => ac (cell w.store j))=inputTape _ _ _ rw [storeEq]; exact cell_layout ac sc M C (f x) end P455FoldDelivery end /- Begin Problem455WriterGuardSpec (from finite-semigroup-identity-bases). -/ section namespace P455WriterGuard open P455WriterTiles (choices choicesRec) open P455WriterQueryLeaves (Env ModelsEnv) open P455PaddedTiles P455GuardProduct open P455Witness (Tag Holds) abbrev Key := Bool × Nat × Nat × Nat def environment (r : Nat) (ts : List Tag) (w : List Nat) (a b : Nat) : Env := (r,ts,[(a,b)],w) def checker (r n : Nat) (ts : List Tag) (w : List Nat) (k : Bool) (a b : Nat) := let e := environment r ts w a b P455EffectiveQMove.capB r w && (if k then P455WriterEdge.funcAccept e n a b else P455WriterSlots.slotAccept e a b) def ValidKey (r : Nat) (M : MachineTable n) (w : List Nat) (k : Bool) (a b : Nat) := P455Closure.Cap r w ∧ ∃ g : Guard, g.isFunc=k ∧ g.anchor.owner=a ∧ g.anchor.mate=b ∧ Holds r (allowed M) (P455SlotProduct.pairMark a b) w (g.query r (system n)) theorem checker_ok {r : Nat} (hr : 0 P455Enum.mem_tags,fun _ _ => by simp [e,environment,P455SlotProduct.pairMark],rfl,hr⟩ unfold checker ValidKey simp only [Bool.and_eq_true,P455EffectiveQMove.cap_iff] apply and_congr_right intro _ cases k with | false => change P455WriterSlots.slotAccept e a b=true ↔ _ rw [P455WriterSlots.slotAccept_ok M h rfl] constructor · rintro ⟨s,ha,hb,ok⟩; exact ⟨.slot s,rfl,ha,hb,ok⟩ · rintro ⟨s|f,k,ha,hb,ok⟩; exact ⟨s,ha,hb,ok⟩; cases k | true => change P455WriterEdge.funcAccept e n a b=true ↔ _ rw [P455WriterEdge.funcAccept_ok M h rfl] constructor · rintro ⟨f,ha,hb,ok⟩; exact ⟨.func f,rfl,ha,hb,ok⟩ · rintro ⟨s|f,k,ha,hb,ok⟩; cases k; exact ⟨f,ha,hb,ok⟩ def wordAt (r : Nat) (kind : Bool) (i : Nat) := (words r kind)[i]?.getD [] def base (r : Nat) (k : Bool) := choices (List.range (words r k).length) (choices (List.range (width k)) (List.range (width k))) def keys (r : Nat) : List Key := [false,true].flatMap fun k => (base r k).map (Prod.mk k) def filtered (r n : Nat) (ts : List Tag) := (keys r).filter fun k => checker r n ts (wordAt r k.1 k.2.1) k.1 k.2.2.1 k.2.2.2 def spec (r : Nat) (k : Key) : P455Packed.Spec := (wordAt r k.1 k.2.1,some [(k.2.2.1,k.2.2.2)]) def family (r n : Nat) (ts : List Tag) := (P455Table.distinct (filtered r n ts)).map (spec r) def key (i : Index r allow ts) : Key := (i.kind,i.pos.val,i.a.val,i.b.val) theorem key_inj : Function.Injective (@key r allow ts) := by rintro ⟨k,i,a,b,_,_⟩ ⟨k',i',a',b',_,_⟩ h change (k,i.val,a.val,b.val)=(k',i'.val,a'.val,b'.val) at h simp only [Prod.mk.injEq] at h obtain ⟨rfl,hi,ha,hb⟩ := h cases Fin.ext hi; cases Fin.ext ha; cases Fin.ext hb; rfl def vals (x : P455Enum.GuardKey r) : Key := (x.1,x.2.1.val,x.2.2.1.val,x.2.2.2.val) private theorem attachKeys (xs : List (P455Enum.GuardKey r)) : xs.attach.map (fun x => vals x.val) = xs.map vals := List.attach_map_val .. theorem wordAt_get (r : Nat) (k : Bool) (i : Fin (words r k).length) : wordAt r k i.val=(words r k).get i := by simp [wordAt,i.isLt] def coreKeys (r : Nat) : List (P455Enum.GuardKey r) := (P455Enum.sigmaCover P455Enum.bools _ (fun k => P455Enum.pairCover (P455Enum.fins (words r k).length) (P455Enum.pairCover (P455Enum.fins (width k)) (P455Enum.fins (width k))))).list theorem key_order (r : Nat) : (coreKeys r).map vals = keys r := by have one (k : Bool) : ((P455Enum.pairCover (P455Enum.fins (words r k).length) (P455Enum.pairCover (P455Enum.fins (width k)) (P455Enum.fins (width k)))).list.map (fun p => @vals r ⟨k,p⟩)) = (base r k).map (Prod.mk k) := by unfold base vals rw [←p455MapFinRange,←p455MapFinRange (n:=width k)] simp only [P455Enum.pairCover,P455Enum.Cover.bind,P455Enum.fins,choices,List.map_flatMap,List.map_map,List.flatMap_map,Function.comp_def] unfold coreKeys keys simp only [P455Enum.sigmaCover,List.map_flatMap,List.map_map,Function.comp_def] exact congrArg (List.flatMap · [false,true]) (funext one) theorem filtered_ok (M : MachineTable n) (hr : 0 @vals r x.val) (List.attach (_ : List (P455Enum.GuardKey r)))) = _ rw [@attachKeys r] apply congrArg (List.map vals); apply List.filter_congr intro x _ apply Bool.eq_iff_iff.mpr simp only [decide_eq_true_eq,vals,wordAt_get,checker_ok hr,ValidKey] theorem family_ok (M : MachineTable n) (hr : 0 whenB (b x) (p x) := Primrec.ite (Primrec.eq.comp hb (.const true)) hp (.const true) theorem localRec {v : A→Env} {n : A→Nat} {f : A→EdgeCertificate} (hv : Primrec v) (hn : Primrec n) (hf : Primrec f) : Primrec fun x => localB (v x) (n x) (f x) := by have a := edgeARec.comp hf; have rt := edgeRightRec.comp hf; have dn := edgeDownRec.comp hf; have di := edgeDiagonalRec.comp hf have rightActive := Primrec.not.comp (flagRec 1 a); have bottom := Primrec.not.comp (flagRec 3 a) exact Primrec.and.comp (whenRec rightActive (rightRec hv hn a rt)) <| Primrec.and.comp (whenRec (Primrec.not.comp (flagRec 0 a)) (rightRec hv hn (edgeLeftRec.comp hf) a)) <| Primrec.and.comp (whenRec bottom (downRec hv hn a dn)) <| Primrec.and.comp (whenRec (Primrec.not.comp (flagRec 2 a)) (downRec hv hn (edgeUpRec.comp hf) a)) (whenRec (Primrec.and.comp rightActive bottom) (Primrec.and.comp (downRec hv hn rt di) (rightRec hv hn dn di))) theorem chosenRec {v : A→Env} {n : A→Nat} {f : A→EdgeCertificate} (hv : Primrec v) (_hn : Primrec n) (hf : Primrec f) : Primrec fun x => chosenB (v x) (n x) (f x) := by have a := edgeARec.comp hf; have b := edgeBRec.comp hf have odd := Primrec.eq.comp (flagRec 4 a) (.const true) have last := Primrec.ite odd (flagRec 0 a) (flagRec 1 a) have next := Primrec.ite (Primrec.eq.comp last (.const true)) (edgeDownRec.comp hf) (Primrec.ite odd (edgeLeftRec.comp hf) (edgeRightRec.comp hf)) have corner := Primrec.and.comp (Primrec.and.comp (Primrec.and.comp (flagRec 2 b) (flagRec 0 b)) (Primrec.not.comp (flagRec 4 b))) (Primrec.not.comp (flagRec 5 b)) exact Primrec.ite (Primrec.eq.comp (Primrec.and.comp last (flagRec 3 a)) (.const true)) (Primrec.and.comp corner (Primrec.and.comp (Primrec.or.comp (portRec hv (.const 4) a b) (portRec hv (.const 4) b a)) (order2Rec hv (ownerRec.comp b) (.const 0) (ownerRec.comp a) (.const 0)))) (Primrec.and.comp (Primrec.eq.comp next b).decide (order2Rec hv (ownerRec.comp a) (.const 0) (ownerRec.comp b) (.const 0))) theorem queryRec {v : A→Env} {n : A→Nat} {f : A→EdgeCertificate} (hv : Primrec v) (hn : Primrec n) (hf : Primrec f) : Primrec fun x => queryB (v x) (n x) (f x) := Primrec.and.comp (nodeMarkedRec hv (edgeARec.comp hf) (.const true)) (Primrec.and.comp (nodeMarkedRec hv (edgeBRec.comp hf) (.const false)) (Primrec.and.comp (localRec hv hn hf) (chosenRec hv hn hf))) theorem namesRec {n : A→Nat} {f : A→EdgeCertificate} (_hn : Primrec n) (hf : Primrec f) : Primrec fun x => P455EdgeProjection.names (system (n x)) (f x) := by have a := edgeARec.comp hf; have b := edgeBRec.comp hf have rightActive := Primrec.not.comp (flagRec 1 a); have bottom := Primrec.not.comp (flagRec 3 a) let cons := @Primrec.list_cons (Node × Bool) _ have fin := cons.comp ((edgeDiagonalRec.comp hf).pair (Primrec.and.comp rightActive bottom)) (.const []) have up := cons.comp ((edgeUpRec.comp hf).pair (Primrec.not.comp (flagRec 2 a))) fin have down := cons.comp ((edgeDownRec.comp hf).pair bottom) up have leftList := cons.comp ((edgeLeftRec.comp hf).pair (Primrec.not.comp (flagRec 0 a))) down have rest := cons.comp ((edgeRightRec.comp hf).pair rightActive) leftList have candidates := cons.comp (a.pair (.const true)) (cons.comp (b.pair (.const true)) rest) have active := P455GraphPrim.filter candidates (Primrec.snd.comp Primrec.snd).to₂ have nodes := Primrec.list_map active (Primrec.fst.comp Primrec.snd).to₂ exact Primrec.list_flatMap nodes (rolesRec.comp Primrec.snd).to₂ theorem sameRec {s t : A→List Nat} (hs : Primrec s) (ht : Primrec t) : Primrec fun x => sameNames (s x) (t x) := Primrec.and.comp (P455FramePrim.allB hs (memRec Primrec.snd (ht.comp Primrec.fst)).to₂) (P455FramePrim.allB ht (memRec Primrec.snd (hs.comp Primrec.fst)).to₂) theorem envRec {r : A→Nat} {ts : A→List (List Bool)} {w : A→List Nat} {k : A→Quad} (hr : Primrec r) (ht : Primrec ts) (hw : Primrec w) (hk : Primrec k) : Primrec fun x => env (r x) (ts x) (w x) (k x) := by have z := Primrec.snd.comp hk exact hr.pair (ht.pair ((Primrec.list_cons.comp ((Primrec.fst.comp hk).pair (Primrec.fst.comp z)) (Primrec.list_cons.comp (Primrec.snd.comp z) (.const []))).pair hw)) theorem testsRec {r n : A→Nat} {ts : A→List (List Bool)} {w : A→List Nat} {k : A→Quad} (hr : Primrec r) (hn : Primrec n) (ht : Primrec ts) (hw : Primrec w) (hk : Primrec k) : Primrec fun x => tests (r x) (n x) (ts x) (w x) (k x) := by have p := Primrec.fst (α:=A) (β:=EdgeCertificate) have f := Primrec.snd (α:=A) (β:=EdgeCertificate) have a := edgeARec.comp f; have b := edgeBRec.comp f; have k := hk.comp p have z := Primrec.snd.comp k; have t := Primrec.snd.comp z have eqB := (Primrec.eq.comp (ownerRec.comp a) (Primrec.fst.comp k)).and <| (Primrec.eq.comp (mateRec.comp a) (Primrec.fst.comp z)).and <| (Primrec.eq.comp (ownerRec.comp b) (Primrec.fst.comp t)).and (Primrec.eq.comp (mateRec.comp b) (Primrec.snd.comp t)) exact Primrec.and.comp (P455FrameProof.capCheck hr hw) (P455GraphPrim.anyB (certificatesRec hw ht) (Primrec.and.comp eqB.decide (Primrec.and.comp (sameRec (hw.comp p) (namesRec (hn.comp p) f)) (queryRec ((envRec hr ht hw hk).comp p) (hn.comp p) f))).to₂) theorem edgesRec {r n : A→Nat} {ts : A→List (List Bool)} (hr : Primrec r) (hn : Primrec n) (ht : Primrec ts) : Primrec fun x => edges (r x) (n x) (ts x) := by apply familyRec hr have p := Primrec.fst.comp (Primrec.fst (α:=A × List Nat) (β:=Quad)) exact testsRec (hr.comp p) (hn.comp p) (ht.comp p) (Primrec.snd.comp Primrec.fst) Primrec.snd end P455WriterEdge end /- Begin Problem455ComputableWriter (from finite-semigroup-identity-bases). -/ section namespace P455ComputableWriter open Turing P455MachineCleanup P455EffectiveMachine P455EffectiveChain open P455MathlibTM P455MathlibCode P455FoldInput def wire : Wire Track where first := cell true .cons second := cell false .bit1 letter b := cell false (P455MathlibCode.letter b) ink b eq := by have h := congrArg (fun (a : Track) => a.2 Turing.PartrecToTM2.K'.main) eq simp [cell,TM2to1.Γ'.inhabited] at h distinct eq := by have h := congrArg (fun (a : Track) => a.2 Turing.PartrecToTM2.K'.main) eq simp [cell,P455MathlibCode.letter] at h flag := Prod.fst flags := ⟨rfl,rfl,rfl,fun _ => rfl⟩ theorem realizes {f : List Bool → List Bool} (hf : Computable f) : ∃ (g r : Nat) (W : Ordinary g r) (A : Alphabet W), ∀ x, Delivers W A x W A (f x) := by obtain ⟨Q,fs,ih,M,guard,run⟩ := P455MathlibFinite.finite_machine hf exact P455FoldDelivery.exact_delivery M wire guard f run end P455ComputableWriter end /- Begin Problem455WriterCatalogueSpec (from finite-semigroup-identity-bases). -/ section /- The complete five-family catalogue from a finite numerical local table. -/ namespace P455WriterCatalogue open P455PaddedTiles P455WriterTiles def capSize (n : Nat) := widthCode n + 16 def build (D : MachineData) : P455SerializePrim.Data := let n := size D let r := capSize n let ts := tags D (r, ts, P455CataloguePrim.primitive r, P455WriterGuard.family r n ts, P455WriterEdge.edges r n ts, P455WriterBinary.bin r ts, P455WriterStructural.structural r ts) theorem build_correct {D : MachineData} {M : MachineTable n} (h : Models D M) : build D = P455SerializePrim.ofPayload (P455Packed.prepared M) := by have hr : 0 < capSize n := by unfold capSize; omega simp only [build,h.dim,tags_correct h] rw [P455WriterGuard.family_ok M hr,P455WriterEdge.edges_correct M hr,P455WriterBinary.bin_correct M, P455WriterStructural.structural_correct hr M] have p := P455PayloadBridge.primitive_field M unfold P455SerializePrim.ofPayload P455Packed.prepared dsimp only [P455Encoded.indices] simp only [capSize] rw [←p] simp only [P455Packed.prepared,P455Encoded.indices] rfl def table (D : MachineData) := P455Packed.serialize (P455SerializePrim.asPayload (build D)) def bits (D : MachineData) := P455TableBits.encode (table D) theorem table_correct {D : MachineData} {M : MachineTable n} (h : Models D M) : table D = P455Packed.serialize (P455Packed.prepared M) := by unfold table rw [build_correct h,P455SerializePrim.as_of] theorem table_represents {D : MachineData} {M : MachineTable n} (h : Models D M) : P455NumericProduct.Represents (table D) (P455Global.monoid M) := by rw [table_correct h] exact P455Packed.serialize_represents M end P455WriterCatalogue end /- Begin Problem455WriterGuard (from finite-semigroup-identity-bases). -/ section namespace P455WriterGuard open P455WriterTiles (choicesRec) open P455PaddedTiles P455GuardProduct open P455Witness (Tag) variable {A : Type} [Primcodable A] theorem widthRec : Primrec width := Primrec.ite (Primrec.eq.comp Primrec.id (.const true)) (.const 8) (.const 43) theorem wordsRec {r : A → Nat} {k : A → Bool} (hr : Primrec r) (hk : Primrec k) : Primrec fun a => words (r a) (k a) := P455GraphPrim.wordsUpTo.comp (Primrec.list_range.comp (widthRec.comp hk)) (Primrec.nat_mul.comp (widthRec.comp hk) hr) theorem wordAtRec {r i : A → Nat} {k : A → Bool} (hr : Primrec r) (hk : Primrec k) (hi : Primrec i) : Primrec fun a => wordAt (r a) (k a) (i a) := Primrec.option_getD.comp (Primrec.list_getElem?.comp (wordsRec hr hk) hi) (.const []) theorem keysRec : Primrec keys := by apply Primrec.list_flatMap (.const [false,true]) apply Primrec₂.mk have r := Primrec.fst (α := Nat) (β := Bool) have k := Primrec.snd (α := Nat) (β := Bool) have ws := Primrec.list_range.comp (widthRec.comp k) apply Primrec.list_map (choicesRec (Primrec.list_range.comp (Primrec.list_length.comp (wordsRec r k))) (choicesRec ws ws)) exact (Primrec.pair (k.comp Primrec.fst) Primrec.snd).to₂ theorem checkerRec {r n a b : A → Nat} {ts : A → List Tag} {w : A → List Nat} {k : A → Bool} (hr : Primrec r) (hn : Primrec n) (ht : Primrec ts) (hw : Primrec w) (hk : Primrec k) (ha : Primrec a) (hb : Primrec b) : Primrec fun x => checker (r x) (n x) (ts x) (w x) (k x) (a x) (b x) := by have mark := Primrec.list_cons.comp (ha.pair hb) (.const []) have e := hr.pair (ht.pair (mark.pair hw)) exact Primrec.and.comp (P455FrameProof.capCheck hr hw) (Primrec.ite (Primrec.eq.comp hk (.const true)) (P455WriterEdge.funcAcceptRec e hn ha hb) (P455WriterSlots.slotAcceptRec e ha hb)) theorem familyRec {r n : A → Nat} {ts : A → List Tag} (hr : Primrec r) (hn : Primrec n) (ht : Primrec ts) : Primrec fun a => family (r a) (n a) (ts a) := by have p := Primrec.snd (α := A) (β := Key) have src := Primrec.fst (α := A) (β := Key) have k := Primrec.fst.comp p have i := Primrec.fst.comp (Primrec.snd.comp p) have a := Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp p)) have b := Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp p)) have w := wordAtRec (hr.comp src) k i have pr : Primrec₂ (fun x (t : Key) => checker (r x) (n x) (ts x) (wordAt (r x) t.1 t.2.1) t.1 t.2.2.1 t.2.2.2) := checkerRec (hr.comp src) (hn.comp src) (ht.comp src) w k a b have f := P455GraphPrim.filter (keysRec.comp hr) pr exact Primrec.list_map (P455CataloguePrim.distinct'.comp f) (w.pair (Primrec.option_some.comp (Primrec.list_cons.comp (a.pair b) (.const [])))).to₂ end P455WriterGuard end /- Begin Problem455CertifiedReduction (from finite-semigroup-identity-bases). -/ section namespace P455CertifiedReduction open P455WriterTiles P455WriterProgram P455SerializePrim P455Table P455TableSemantics open P455MachineCleanup P455MachineTable P455EffectiveMachine P455EffectiveWriter P455EffectiveChain open P455NumericProduct P455PaddedTiles abbrev Catalogue := MachineData → Data def Correct (c : Catalogue) := ∀ {n} (M : MachineTable n) (d : MachineData), Models d M → asPayload (c d)=P455Packed.prepared M def materialize (c : Catalogue) (d : MachineData) := P455TableValidate.safe (P455Packed.serialize (asPayload (c d))) def codeTable (c : Catalogue) (s : List Bool) := materialize c (fromCodeBits s) def selfTable (c : Catalogue) (s : List Bool) := materialize c (fromBits s) theorem buildRec {c : Catalogue} (hc : Primrec c) : Primrec (materialize c) := P455TableValidate.safeRec.comp (P455SerializePrim.serialize.comp hc) theorem codeRec {c : Catalogue} (hc : Primrec c) : Primrec (codeTable c) := (buildRec hc).comp Cert.fromCodeBits' theorem selfRec {c : Catalogue} (hc : Primrec c) : Primrec (selfTable c) := (buildRec hc).comp Cert.fromBits' theorem finite_monoid (c : Catalogue) (d : MachineData) : SemigroupTable (materialize c d) ∧ HasUnit (materialize c d) := P455TableValidate.monoid _ theorem builds {c : Catalogue} (hc : Correct c) (M : Ordinary ng nq) {d : MachineData} (h : Models d (compile (normalized M))) : Represents (materialize c d) (P455MachineReduction.model M) := by unfold materialize; rw [hc _ d h] obtain ⟨X,e,⟨iso⟩⟩ := P455PackedOutput.alternative_represents M change P455Packed.serialize _=matrix X at e exact ⟨X,by rw [e,P455TableValidate.identity (output_laws iso)],⟨iso⟩⟩ theorem code_presents {c : Catalogue} (hc : Correct c) (C : Code ng nq) (s : C.Safe) : Represents (codeTable c C.bits) (P455MachineReduction.model (C.machine s)) := builds hc _ (fromCodeBits_spec C s) theorem code_basis {c : Catalogue} (hc : Correct c) (C : Code ng nq) (s : C.Safe) : P455PureSemigroup.Basis (codeTable c C.bits) ↔ ¬ ∃ t, stopped (C.machine s) t := by obtain ⟨X,e,⟨iso⟩⟩ := code_presents hc C s rw [e,P455PureSemigroup.basis_iff (output_laws iso).1,P455TableSemantics.basis_iff iso] exact P455Decision.ordinary_equivalence _ theorem self_presents {c : Catalogue} (hc : Correct c) (P : Ordinary ng nq) (B : Alphabet P) : Represents (selfTable c (selfBits P B)) (P455MachineReduction.model (diagonalInput P B).2) := builds hc _ (fromBits_self P B) theorem self_basis {c : Catalogue} (hc : Correct c) (P : Ordinary ng nq) (B : Alphabet P) : P455PureSemigroup.Basis (selfTable c (selfBits P B)) ↔ ¬ SelfHalt P B := by obtain ⟨X,e,⟨iso⟩⟩ := self_presents hc P B rw [e,P455PureSemigroup.basis_iff (output_laws iso).1,P455TableSemantics.basis_iff iso] exact diagonal_basis P B theorem presentation {c : Catalogue} (hc : Correct c) (recProof : Primrec c) : P455TableDecision.PresentationWriterExists := by have hf := P455NumericProductPrim.encode.comp (selfRec recProof) obtain ⟨g,q,W,A,run⟩ := P455ComputableWriter.realizes hf.to_comp refine ⟨g,q,W,A,A,?_⟩ intro k s P B obtain ⟨X,e,iso⟩ := self_presents hc P B refine ⟨X,iso,?_⟩ simpa only [Function.comp_apply,←e] using run (selfBits P B) end P455CertifiedReduction end /- Begin Problem455ComputableReduction (from finite-semigroup-identity-bases). -/ section namespace P455ComputableReduction /-- The previously isolated operational assumption follows from the standard computability of the first-order machine-to-catalogue map. -/ theorem presentation (code : Computable P455PayloadBridge.selfPayload) : P455TableDecision.PresentationWriterExists := by obtain ⟨g,r,W,A,run⟩ := P455ComputableWriter.realizes (P455PayloadBridge.selfOutput_computable code) exact ⟨g,r,W,A,A,P455PackedOutput.delivers_presentation W A A run⟩ theorem reduction (code : Computable P455PayloadBridge.selfPayload) : ¬ P455TableDecision.PureDeciderExists := P455TableDecision.no_table_algorithm_of_presentation_writer (presentation code) end P455ComputableReduction end /- Begin Problem455WriterCatalogue (from finite-semigroup-identity-bases). -/ section namespace P455WriterCatalogue open P455PaddedTiles P455WriterTiles theorem capRec : Primrec capSize := Primrec.nat_add.comp (Primrec.nat_add.comp (.const 6) (Primrec.nat_mul.comp (.const 4) (Primrec.succ.comp Primrec.id))) (.const 16) theorem buildRec : Primrec build := by have n : Primrec size := Primrec.fst have r := capRec.comp n have ts := P455WriterTiles.tagsRec exact r.pair (ts.pair ((P455CataloguePrim.primitive'.comp r).pair ((P455WriterGuard.familyRec r n ts).pair ((P455WriterEdge.edgesRec r n ts).pair ((P455WriterBinary.binRec r ts).pair (P455WriterStructural.structuralRec r ts)))))) theorem tableRec : Primrec table := P455SerializePrim.serialize.comp buildRec theorem bitsRec : Primrec bits := P455SerializePrim.bits.comp buildRec end P455WriterCatalogue end /- Begin Problem455StandardDecision (from finite-semigroup-identity-bases). -/ section namespace P455StandardDecision open P455MachineCleanup P455EffectiveMachine P455EffectiveChain P455RelabeledChain open P455TableBits P455BooleanReader theorem bit_decider {f : List Bool → Bool} (hf : Computable f) : ∃ (g q : Nat) (M : Ordinary g q) (A : Alphabet M) (ans : Fin q → Bool), ∀ x, Answers M A ans x (f x) := by have single : Computable (fun x => [f x]) := Primrec.list_cons.to_comp.comp hf (Computable.const []) obtain ⟨g,r,W,A,writer⟩ := P455ComputableWriter.realizes single refine ⟨_,_,combined W A reader bits,inputs W A A reader bits,out r ans,?_⟩ intro x exact answers_combined W A A reader bits ans (writer _) (reads_bit _) theorem ordinary_of_standard : StandardDecider → P455TableDecision.PureDeciderExists := by rintro ⟨f,hf,correct⟩ obtain ⟨g,q,M,A,ans,run⟩ := bit_decider hf exact ⟨g,q,M,A,ans,fun T valid => ⟨_,run (encode T),correct T valid⟩⟩ theorem standard_reduction (code : Computable P455PayloadBridge.selfPayload) : ¬StandardDecider := fun alleged => P455ComputableReduction.reduction code (ordinary_of_standard alleged) theorem table_valid (x : List Bool) : P455TableSemantics.SemigroupTable (P455PackedOutput.selfTable x) := by unfold P455PackedOutput.selfTable cases P455MachineParse.blankSource x with | none => exact (P455TableSemantics.output_laws P455RawReduction.singletonPresents).1 | some src => obtain ⟨_,_,M⟩ := src obtain ⟨_,h,⟨pres⟩⟩ := P455PackedOutput.alternative_represents M change P455TableSemantics.SemigroupTable (P455PackedOutput.alternative M) rw [h] exact (P455TableSemantics.output_laws pres).1 def PromiseOn {α : Type} [Primcodable α] (representation : P455Table.Matrix → α) := ∃ p : α →. Bool, Partrec p ∧ ∀ T, P455TableSemantics.SemigroupTable T → ∃ b ∈ p (representation T), (b=true ↔ P455PureSemigroup.Basis T) /-- Only the composite on machine codes is totalized. The alleged table decider is not required to return any answer on invalid encodings. -/ theorem promise_of_encoding {α : Type} [Primcodable α] (representation : P455Table.Matrix → α) (tables : List Bool → P455Table.Matrix) (computes : Computable (fun x => representation (tables x))) (valid : ∀ x, P455TableSemantics.SemigroupTable (tables x)) (correct : ∀ {g q} (M : Ordinary g q) (A : Alphabet M), P455PureSemigroup.Basis (tables (selfBits M A)) ↔ ¬SelfHalt M A) : ¬PromiseOn representation := by rintro ⟨p,hp,good⟩ let bits x := representation (tables x) have total (x : List Bool) : (p (bits x)).Dom := by obtain ⟨b,hb,_⟩ := good _ (valid x) exact Part.dom_iff_mem.mpr ⟨_,hb⟩ let f (x : List Bool) := (p (bits x)).get (total x) have hf : Computable f := (hp.comp computes).of_eq_tot (fun x => Part.get_mem (total x)) have exact_result (x : List Bool) : f x=true ↔ P455PureSemigroup.Basis (tables x) := by obtain ⟨b,hb,claim⟩ := good _ (valid x) have same : f x=b := Part.mem_unique (Part.get_mem (total x)) hb rw [same]; exact claim obtain ⟨_,_,D,A,ans,run⟩ := bit_decider hf apply no_self_decider D A (fun q => !(ans q)) intro g q M B let x := selfBits M B obtain ⟨t,stop,verdict⟩ := run x refine ⟨t,stop,?_⟩ have hs := (exact_result x).trans (correct M B) change (!(ans (follow D (inputConfig D A x) t).state))=true ↔ SelfHalt M B rw [verdict] classical cases eq : f x <;> simp_all /-- A partial decider on canonically serialized rows. -/ theorem promise_of_bits (tables : List Bool → P455Table.Matrix) (computes : Computable (fun x => P455TableBits.encode (tables x))) (valid : ∀ x, P455TableSemantics.SemigroupTable (tables x)) (correct : ∀ {g q} (M : Ordinary g q) (A : Alphabet M), P455PureSemigroup.Basis (tables (selfBits M A)) ↔ ¬SelfHalt M A) : ¬PromiseDecider := promise_of_encoding P455TableBits.encode tables computes valid correct /-- The natural matrix itself is the input. A decider may diverge on every malformed or nonassociative matrix. -/ theorem numeric_promise (tables : List Bool → P455Table.Matrix) (computes : Computable tables) (valid : ∀ x, P455TableSemantics.SemigroupTable (tables x)) (correct : ∀ {g q} (M : Ordinary g q) (A : Alphabet M), P455PureSemigroup.Basis (tables (selfBits M A)) ↔ ¬SelfHalt M A) : ¬PromiseOn (id : P455Table.Matrix → P455Table.Matrix) := promise_of_encoding id tables computes valid correct theorem promise_of_tables (tables : List Bool → P455Table.Matrix) (computes : Computable tables) (valid : ∀ x, P455TableSemantics.SemigroupTable (tables x)) (correct : ∀ {g q} (M : Ordinary g q) (A : Alphabet M), P455PureSemigroup.Basis (tables (selfBits M A)) ↔ ¬SelfHalt M A) : ¬PromiseDecider := promise_of_bits tables (P455NumericProductPrim.encode.to_comp.comp computes) valid correct theorem promise_reduction (code : Computable P455PayloadBridge.selfPayload) : ¬PromiseDecider := promise_of_bits P455PackedOutput.selfTable (P455PayloadBridge.selfOutput_computable code) table_valid P455PackedOutput.pure_basis_on_self end P455StandardDecision end /- Begin Problem455Undecidability (from finite-semigroup-identity-bases). -/ section namespace P455Undecidability open P455Table P455TableSemantics P455EffectiveMachine P455MachineCleanup open P455PureSemigroup P455BinaryTerms P455CertifiedReduction theorem catalogue_ok : Correct P455WriterCatalogue.build := by intro n M d h rw [P455WriterCatalogue.build_correct h,P455SerializePrim.as_of] /-- Total numerical array function on all binary inputs, with a proof in mathlib's standard primitive recursive model. -/ def multiplicationTable := codeTable P455WriterCatalogue.build theorem table_primitive_recursive : Primrec multiplicationTable := codeRec P455WriterCatalogue.buildRec theorem table_is_finite_monoid (s : List Bool) : SemigroupTable (multiplicationTable s) ∧ HasUnit (multiplicationTable s) := finite_monoid P455WriterCatalogue.build (P455WriterProgram.fromCodeBits s) theorem presents_exact_model (C : Code ng nq) (safe : C.Safe) : P455NumericProduct.Represents (multiplicationTable C.bits) (P455MachineReduction.model (C.machine safe)) := code_presents catalogue_ok C safe theorem blank_tape_reduction (C : Code ng nq) (safe : C.Safe) : Basis (multiplicationTable C.bits) ↔ ¬ ∃ t, stopped (C.machine safe) t := code_basis catalogue_ok C safe theorem presentation_writer_exists : P455TableDecision.PresentationWriterExists := presentation catalogue_ok P455WriterCatalogue.buildRec theorem no_table_decider : ¬P455TableDecision.PureDeciderExists := P455TableDecision.no_table_algorithm_of_presentation_writer presentation_writer_exists theorem no_bit_promise_decider : ¬P455BooleanReader.PromiseDecider := P455StandardDecision.promise_of_tables (selfTable P455WriterCatalogue.build) (selfRec P455WriterCatalogue.buildRec).to_comp (fun x => (finite_monoid P455WriterCatalogue.build (P455WriterProgram.fromBits x)).1) (self_basis catalogue_ok) theorem no_matrix_promise_decider : ¬P455StandardDecision.PromiseOn (id : Matrix→Matrix) := P455StandardDecision.numeric_promise (selfTable P455WriterCatalogue.build) (selfRec P455WriterCatalogue.buildRec).to_comp (fun x => (finite_monoid P455WriterCatalogue.build (P455WriterProgram.fromBits x)).1) (self_basis catalogue_ok) /-- On every finite associative nonempty multiplication array, the alleged algorithm must terminate and correctly test equality of its identity theory with the semantic consequences of a finite list of equations in the language having only variables and multiplication. -/ theorem finite_semigroup_finite_basis_undecidable : ¬ ∃ p : Matrix →. Bool, Partrec p ∧ ∀ T (valid : SemigroupTable T), ∃ b ∈ p T, (b=true ↔ ∃ R : List (Term×Term), ∀ s t, (∀ a : Nat→Fin T.length, P455StatementAudit.val valid a s=P455StatementAudit.val valid a t) ↔ P455SemanticConsequence.entails (fun u v => (u,v)∈R) s t) := by rintro ⟨p,hp,answers⟩ apply no_matrix_promise_decider refine ⟨p,hp,?_⟩ intro T valid obtain ⟨b,halt,spec⟩ := answers T valid exact ⟨b,halt,spec.trans (P455SemanticConsequence.public_basis valid).symm⟩ end P455Undecidability end #print axioms P455Undecidability.finite_semigroup_finite_basis_undecidable