File size: 32,534 Bytes
ea76aac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
import Mathlib
import OAI.Computability.DirectedFeedback.Machines.MachineOverlayTable

namespace OAI

section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section
section

section

namespace DFVSGames.Foundations.Complexity.MachinePaddedOverlay

open Turing MachineComposition MachineCloudPadding
open PCP

variable {d : Nat}

abbrev BaseTable := PreprocessingStageMaps.BaseTable
abbrev baseDegree := Expanders.baseDegree
abbrev overlayDegree := PreprocessingRegularTables.internalDegree
abbrev Tape := MachineVertexPadding.Tape ⊕ (MachineExpanderFamily.Tape ⊕ MachineOverlayTable.Tape)
abbrev Alphabet (_ : Tape) := Bool
abbrev Label (d : Nat) := MachineVertexPadding.Label d ⊕ (MachineExpanderFamily.Label baseDegree ⊕ MachineOverlayTable.Label d overlayDegree)
abbrev State (d : Nat) := MachineVertexPadding.State (MachineExpanderFamily.State Unit baseDegree × MachineOverlayTable.State Unit d overlayDegree)

theorem overlayDegree_positive : 0 < overlayDegree :=
  Nat.mul_pos MachineExpanderFamily.baseDegree_positive MachineExpanderFamily.baseDegree_positive

def paddingTape (k : MachineVertexPadding.Tape) : Tape := .inl k

def paddingView : Tape → Option MachineVertexPadding.Tape
  | .inl k => some k
  | .inr _ => none

@[simp] theorem paddingView_left (k : MachineVertexPadding.Tape) : paddingView (paddingTape k) = some k := rfl

theorem paddingView_right (j : Tape) (k : MachineVertexPadding.Tape)
    (h : paddingView j = some k) : paddingTape k = j := by
  cases j with
  | inl j => cases Option.some.inj h; rfl
  | inr j => simp [paddingView] at h

def familyTape (k : MachineExpanderFamily.Tape) : Tape :=
  if k = .inr .remainingLevel then .inl .level else .inr (.inl k)

def familyView : Tape → Option MachineExpanderFamily.Tape
  | .inl .level => some (.inr .remainingLevel)
  | .inr (.inl k) => if k = .inr .remainingLevel then none else some k
  | _ => none

@[simp] theorem familyView_left (k : MachineExpanderFamily.Tape) : familyView (familyTape k) = some k := by
  by_cases h : k = .inr .remainingLevel
  · subst k; rfl
  · simp [familyTape, familyView, h]

theorem familyView_right (j : Tape) (k : MachineExpanderFamily.Tape)
    (h : familyView j = some k) : familyTape k = j := by
  rcases j with j | j
  · cases j <;> simp_all [familyView, familyTape]
  · rcases j with j | j
    · by_cases hj : j = .inr .remainingLevel <;> simp_all [familyView, familyTape]
    · simp [familyView] at h

def overlayTape (k : MachineOverlayTable.Tape) : Tape :=
  if k = MachineOverlayTable.graphArchive then .inl .output
  else if k = MachineOverlayTable.expanderArchive then .inr (.inl MachineExpanderFamily.tableTape)
  else .inr (.inr k)

def overlayView : Tape → Option MachineOverlayTable.Tape
  | .inl .output => some MachineOverlayTable.graphArchive
  | .inr (.inl k) => if k = MachineExpanderFamily.tableTape then some MachineOverlayTable.expanderArchive else none
  | .inr (.inr k) =>
      if k = MachineOverlayTable.graphArchive ∨ k = MachineOverlayTable.expanderArchive then none else some k
  | _ => none

@[simp] theorem overlayView_left (k : MachineOverlayTable.Tape) : overlayView (overlayTape k) = some k := by
  by_cases hg : k = MachineOverlayTable.graphArchive
  · subst k; rfl
  · by_cases he : k = MachineOverlayTable.expanderArchive
    · subst k; rfl
    · simp [overlayTape, overlayView, hg, he]

theorem overlayView_right (j : Tape) (k : MachineOverlayTable.Tape)
    (h : overlayView j = some k) : overlayTape k = j := by
  rcases j with j | j
  · cases j <;> simp_all [overlayView, overlayTape, MachineOverlayTable.graphArchive]
  · rcases j with j | j
    · by_cases hj : j = MachineExpanderFamily.tableTape
      · subst j
        have hk : MachineOverlayTable.expanderArchive = k := by
          simpa [overlayView] using h
        subst k
        rfl
      · simp [overlayView, hj] at h
    · by_cases hg : j = MachineOverlayTable.graphArchive
      · simp [overlayView, hg] at h
      · by_cases he : j = MachineOverlayTable.expanderArchive
        · simp [overlayView, he] at h
        · simp_all [overlayView, overlayTape]

def paddingLabel (l : MachineVertexPadding.Label d) : Label d := .inl l
def familyLabel (l : MachineExpanderFamily.Label baseDegree) : Label d := .inr (.inl l)
def overlayLabel (l : MachineOverlayTable.Label d overlayDegree) : Label d := .inr (.inr l)
def main : Label d := paddingLabel (.splitCode .copyFirst)
def familyEntry : Label d := familyLabel (.inr .initialize)
def overlayEntry : Label d := overlayLabel (.inl .copyFirst)

def familyStates (d : Nat) :
    (MachineExpanderFamily.State Unit baseDegree × ((MachineOverlayTable.State Unit d overlayDegree × Bool) × Option Bool)) ≃
      State d where
  toFun s := (((s.1, s.2.1.1), s.2.1.2), s.2.2)
  invFun s := (s.1.1.1, ((s.1.1.2, s.1.2), s.2))
  left_inv := by rintro ⟨f, ⟨⟨o, b⟩, r⟩⟩; rfl
  right_inv := by rintro ⟨⟨⟨f, o⟩, b⟩, r⟩; rfl

def overlayStates (d : Nat) :
    (MachineOverlayTable.State Unit d overlayDegree × ((MachineExpanderFamily.State Unit baseDegree × Bool) × Option Bool)) ≃
      State d where
  toFun s := (((s.2.1.1, s.1), s.2.1.2), s.2.2)
  invFun s := (s.1.1.2, ((s.1.1.1, s.1.2), s.2))
  left_inv := by rintro ⟨o, ⟨⟨f, b⟩, r⟩⟩; rfl
  right_inv := by rintro ⟨⟨⟨f, o⟩, b⟩, r⟩; rfl

def familySource (H : BaseTable) (d : Nat) : MachineExpanderFamily.Label baseDegree →
    TM2.Stmt MachineExpanderFamily.BoolAlphabet (MachineExpanderFamily.Label baseDegree) (State d) :=
  MachineStateEquiv.program (familyStates d) (MachineStateFrame.frameProgram
    (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H MachineExpanderFamily.baseDegree_cloud_gt_one))

def overlaySource (d : Nat) (hd : 0 < d) : MachineOverlayTable.Label d overlayDegree →
    TM2.Stmt (fun _ : MachineOverlayTable.Tape => Bool) (MachineOverlayTable.Label d overlayDegree) (State d) :=
  MachineStateEquiv.program (overlayStates d) (MachineStateFrame.frameProgram
    (MachineOverlayTable.program d overlayDegree hd overlayDegree_positive))

def program (H : BaseTable) (d : Nat) (hd : 0 < d) :
    Label d → TM2.Stmt Alphabet (Label d) (State d)
  | .inl l => Placement.statement paddingTape paddingLabel (some familyEntry) (MachineVertexPadding.program d hd l)
  | .inr (.inl l) => Placement.statement familyTape familyLabel (some overlayEntry)
      (familySource H d l)
  | .inr (.inr l) => Placement.statement overlayTape overlayLabel none (overlaySource d hd l)

def clean (H : BaseTable) (d : Nat) (hd : 0 < d) : State d :=
  (((MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H (),
    MachineOverlayTable.clean d overlayDegree hd overlayDegree_positive ()), false), none)

def memory (input padded level rotor count output : List Bool) : Tape → List Bool
  | .inl k => MachineVertexPadding.memory input padded [] [] [] level [] [] k
  | .inr (.inl (.inl (.inl .table))) => rotor
  | .inr (.inl (.inr .currentSize)) => count
  | .inr (.inl _) => []
  | .inr (.inr k) => if k = MachineOverlayTable.output then output else []

def padded {n d : Nat} (t : PortTables.Table n d) :=
  PreprocessingPaddingTables.pad t (PreprocessingLevels.le_paddedSize n)

def rotor (H : BaseTable) (n : Nat) : List Bool :=
  encodeWords (ExpanderTableWords.rotationWords
    (ExpanderTables.family H (PreprocessingLevels.boundedLevel n)))

def initialTapes {n d : Nat} (t : PortTables.Table n d) : Tape → List Bool :=
  memory (PortTables.tableBits t) [] [] [] [] []

def paddedTapes {n d : Nat} (t : PortTables.Table n d) : Tape → List Bool :=
  memory (PortTables.tableBits t) (PortTables.tableBits (padded t))
    (encodeWord (PreprocessingLevels.boundedLevel n)) [] [] []

def familyTapes (H : BaseTable) {n d : Nat} (t : PortTables.Table n d) : Tape → List Bool :=
  memory (PortTables.tableBits t) (PortTables.tableBits (padded t))
    (encodeWord 0) (rotor H n) (encodeWord (PreprocessingLevels.paddedSize n)) []

def finalTapes (H : BaseTable) {n d : Nat} (t : PortTables.Table n d) : Tape → List Bool :=
  memory (PortTables.tableBits t) (PortTables.tableBits (padded t))
    (encodeWord 0) (rotor H n) (encodeWord (PreprocessingLevels.paddedSize n))
    (PortTables.tableBits (PreprocessingStageMaps.paddedOverlay H d ⟨n, t⟩).2)

private def placeExecution_inline_MachinePaddedOverlay {K Λ S : Type} [DecidableEq K]
    (tape : K → Tape) (view : Tape → Option K)
    (left : ∀ k, view (tape k) = some k)
    (right : ∀ j k, view j = some k → tape k = j)
    (labels : Λ → Label d) (exit : Option (Label d)) (extra : Tape → List Bool)
    (source : Λ → TM2.Stmt (fun _ : K => Bool) Λ S)
    (target : Label d → TM2.Stmt Alphabet (Label d) S)
    (atLabels : ∀ l, target (labels l) = Placement.statement tape labels exit (source l))
    {a b : TM2.Cfg (fun _ : K => Bool) Λ S} {budget : Nat}
    (run : StateTransition.EvalsToInTime (TM2.step source) a (some b) budget) :
    StateTransition.EvalsToInTime (TM2.step target)
      (Placement.configuration view labels exit extra a)
      (some (Placement.configuration view labels exit extra b)) budget :=
  liftExecutionInTime _ _ _
    (Placement.step_simulation tape view left right labels exit extra source target atLabels) run

theorem padding_initial_memory (input : List Bool) :
    Placement.tapes paddingView (MachineVertexPadding.memory input [] [] [] [] [] [] []) (fun _ => []) =
      memory input [] [] [] [] [] := by
  funext k
  rcases k with k | k
  · rfl
  · rcases k with k | k
    · rcases k with k | k
      · rcases k with k | k <;> cases k <;> rfl
      · cases k <;> rfl
    · simp [Placement.tapes, paddingView, memory]

theorem padding_final_memory (input output level : List Bool) :
    Placement.tapes paddingView (MachineVertexPadding.memory input output [] [] [] level [] []) (fun _ => []) =
      memory input output level [] [] [] := by
  funext k
  rcases k with k | k
  · rfl
  · rcases k with k | k
    · rcases k with k | k
      · rcases k with k | k <;> cases k <;> rfl
      · cases k <;> rfl
    · simp [Placement.tapes, paddingView, memory]

noncomputable def paddingInTime (H : BaseTable) {n d : Nat} (hd : 0 < d) (t : PortTables.Table n d) :
    StateTransition.EvalsToInTime (TM2.step (program H d hd))
      ⟨some main, clean H d hd, initialTapes t⟩
      (some ⟨some familyEntry, clean H d hd, paddedTapes t⟩)
      ((MachineVertexPadding.timePolynomial d).eval (PortTables.tableBits t).length) := by
  let ambient := (MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H (),
    MachineOverlayTable.clean d overlayDegree hd overlayDegree_positive ())
  have run := placeExecution_inline_MachinePaddedOverlay paddingTape paddingView paddingView_left paddingView_right
    paddingLabel (some familyEntry) (fun _ => []) (MachineVertexPadding.program d hd) (program H d hd)
    (fun _ => rfl) (MachineVertexPadding.vertexPaddingInTime hd t ambient none)
  simpa only [Placement.configuration, Placement.label, padding_initial_memory,
    padding_final_memory, initialTapes, paddedTapes, padded, main, clean, ambient] using run

theorem family_initial_memory (input output : List Bool) (level : Nat) :
    Placement.tapes familyView
      (MachineExpanderFamily.toBoolTapes (MachineExpanderFamily.initialTapes level []))
      (memory input output (encodeWord level) [] [] []) =
      memory input output (encodeWord level) [] [] [] := by
  funext k
  rcases k with k | k
  · cases k <;> simp [Placement.tapes, familyView, memory,
      MachineVertexPadding.memory, MachineExpanderFamily.toBoolTapes,
      MachineExpanderFamily.toBoolWord, MachineExpanderFamily.initialTapes,
      MachineEmbedding.tapes]
  · rcases k with k | k
    · rcases k with k | k
      · rcases k with k | k <;> cases k <;>
          simp [Placement.tapes, familyView, memory, MachineExpanderFamily.toBoolTapes,
            MachineExpanderFamily.toBoolWord, MachineExpanderFamily.initialTapes,
            MachineExpanderFamily.tableFrame, MachineEmbedding.tapes]
      · cases k <;>
          simp [Placement.tapes, familyView, memory, MachineExpanderFamily.toBoolTapes,
            MachineExpanderFamily.toBoolWord, MachineExpanderFamily.initialTapes,
            MachineEmbedding.tapes]
    · rfl

theorem family_final_memory (H : BaseTable) (input output : List Bool) (level : Nat) :
    Placement.tapes familyView
      (MachineExpanderFamily.toBoolTapes (MachineExpanderFamily.familyTapes H level []))
      (memory input output (encodeWord level) [] [] []) =
      memory input output (encodeWord 0)
        (encodeWords (ExpanderTableWords.rotationWords (ExpanderTables.family H level)))
        (encodeWord (ExpanderTables.vertexCount overlayDegree level)) [] := by
  funext k
  rcases k with k | k
  · cases k <;> simp [Placement.tapes, familyView, memory,
      MachineVertexPadding.memory, MachineExpanderFamily.toBoolTapes,
      MachineExpanderFamily.toBoolWord, MachineExpanderFamily.familyTapes,
      MachineExpanderFamily.boundaryTapes, MachineExpanderFamily.extraFrame,
      MachineEmbedding.tapes]
  · rcases k with k | k
    · rcases k with k | k
      · rcases k with k | k <;> cases k <;>
          simp [Placement.tapes, familyView, memory, MachineExpanderFamily.toBoolTapes,
            MachineExpanderFamily.toBoolWord, MachineExpanderFamily.familyTapes,
            MachineExpanderFamily.boundaryTapes, MachineExpanderFamily.tableFrame,
            MachineEmbedding.tapes]
      · cases k <;>
          simp [Placement.tapes, familyView, memory, MachineExpanderFamily.toBoolTapes,
            MachineExpanderFamily.toBoolWord, MachineExpanderFamily.familyTapes,
            MachineExpanderFamily.boundaryTapes, MachineExpanderFamily.extraFrame,
            MachineEmbedding.tapes, overlayDegree, PreprocessingRegularTables.internalDegree,
            ExpanderRowControl.degree]
    · simp [Placement.tapes, familyView, memory]

noncomputable def familyInTime (H : BaseTable) {n d : Nat} (hd : 0 < d)
    (t : PortTables.Table n d) :
    StateTransition.EvalsToInTime (TM2.step (program H d hd))
      ⟨some familyEntry, clean H d hd, paddedTapes t⟩
      (some ⟨some overlayEntry, clean H d hd, familyTapes H t⟩)
      (MachineExpanderFamilyBounds.inputCoefficient * (n + 1)^5) := by
  let f := MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H ()
  let o := MachineOverlayTable.clean d overlayDegree hd overlayDegree_positive ()
  have caller : MachineExpanderFamily.caller f = () := Subsingleton.elim _ _
  have castRun := MachineAlphabetTransport.successfulExecutionInTime
    MachineExpanderFamily.alphabet_eq
    (MachineExpanderFamily.program MachineExpanderFamily.baseDegree_positive H
      MachineExpanderFamily.baseDegree_cloud_gt_one)
    (MachineExpanderFamily.paddedFamilyInTime H n f [])
  have boolRun : StateTransition.EvalsToInTime
      (TM2.step (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H
        MachineExpanderFamily.baseDegree_cloud_gt_one))
      ⟨some (.inr .initialize), f, MachineExpanderFamily.toBoolTapes
        (MachineExpanderFamily.initialTapes (PreprocessingLevels.boundedLevel n) [])⟩
      (some ⟨none, f, MachineExpanderFamily.toBoolTapes
        (MachineExpanderFamily.familyTapes H (PreprocessingLevels.boundedLevel n) [])⟩)
      (MachineExpanderFamilyBounds.inputCoefficient * (n + 1)^5) := by
    simpa only [MachineExpanderFamily.boolView, MachineExpanderFamily.configuration_toBool,
      caller] using castRun
  have framed := MachineStateFrame.frameExecution
    (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H
      MachineExpanderFamily.baseDegree_cloud_gt_one) ((o, false), (none : Option Bool)) boolRun
  have transported := MachineStateEquiv.execution (familyStates d)
    (MachineStateFrame.frameProgram
      (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H
        MachineExpanderFamily.baseDegree_cloud_gt_one)) framed
  have sourceRun : StateTransition.EvalsToInTime (TM2.step (familySource H d))
      ⟨some (.inr .initialize), clean H d hd, MachineExpanderFamily.toBoolTapes
        (MachineExpanderFamily.initialTapes (PreprocessingLevels.boundedLevel n) [])⟩
      (some ⟨none, clean H d hd, MachineExpanderFamily.toBoolTapes
        (MachineExpanderFamily.familyTapes H (PreprocessingLevels.boundedLevel n) [])⟩)
      (MachineExpanderFamilyBounds.inputCoefficient * (n + 1)^5) := by
    simpa only [familySource, MachineStateEquiv.configuration,
      MachineStateFrame.frameConfiguration, Option.map_some, familyStates,
      Equiv.coe_fn_mk, clean, f, o]
      using transported
  have run := placeExecution_inline_MachinePaddedOverlay familyTape familyView familyView_left familyView_right
    familyLabel (some overlayEntry) (paddedTapes t) (familySource H d) (program H d hd)
    (fun _ => rfl) sourceRun
  have finishRaw := family_final_memory H (PortTables.tableBits t)
    (PortTables.tableBits (padded t)) (PreprocessingLevels.boundedLevel n)
  have hsize : ExpanderTables.vertexCount overlayDegree (PreprocessingLevels.boundedLevel n) =
      PreprocessingLevels.paddedSize n := PreprocessingLevels.table_vertexCount_eq_paddedSize n
  have count : memory (PortTables.tableBits t) (PortTables.tableBits (padded t))
      (encodeWord 0) (rotor H n)
      (encodeWord (ExpanderTables.vertexCount overlayDegree (PreprocessingLevels.boundedLevel n))) [] =
      familyTapes H t :=
    congrArg (fun size => memory (PortTables.tableBits t) (PortTables.tableBits (padded t))
      (encodeWord 0) (rotor H n) (encodeWord size) []) hsize
  have finish := finishRaw.trans count
  simpa only [Placement.configuration, Placement.label, paddedTapes,
    family_initial_memory, finish, familyEntry] using run

theorem rotationWords_resize {n m q : Nat} (h : n = m) (H : ExpanderTables.Table n q) :
    ExpanderTableWords.rotationWords (PreprocessingRegularTables.resizeTable h H) =
      ExpanderTableWords.rotationWords H := by
  cases h
  rfl

theorem rotor_familyAt (H : BaseTable) (n : Nat) :
    MachineOverlayTable.rawExpander (PreprocessingStageMaps.familyAt H n) = rotor H n := by
  unfold MachineOverlayTable.rawExpander PreprocessingStageMaps.familyAt rotor
  exact congrArg encodeWords
    (rotationWords_resize (PreprocessingLevels.table_vertexCount_eq_paddedSize n)
      (ExpanderTables.family H (PreprocessingLevels.boundedLevel n)))

theorem overlay_memory (input graph raw count output : List Bool) :
    Placement.tapes overlayView
      (MachineOverlayTable.memory graph raw [] [] [] [] [] [] [] output)
      (memory input graph (encodeWord 0) raw count []) =
      memory input graph (encodeWord 0) raw count output := by
  funext k
  rcases k with k | k
  · cases k <;> simp [Placement.tapes, overlayView, memory, MachineVertexPadding.memory,
      MachineOverlayTable.memory, MachineOverlayTable.graphArchive]
  · rcases k with k | k
    · rcases k with k | k
      · rcases k with k | k <;> cases k <;>
          simp [Placement.tapes, overlayView, memory, MachineExpanderFamily.tableTape,
            MachineOverlayTable.memory, MachineOverlayTable.expanderArchive]
      · cases k <;>
          simp [Placement.tapes, overlayView, memory, MachineExpanderFamily.tableTape,
            ]
    · rcases k with k | k <;> fin_cases k <;>
        simp [Placement.tapes, overlayView, memory, MachineOverlayTable.memory,
          MachineOverlayTable.graphArchive, MachineOverlayTable.expanderArchive,
          MachineOverlayTable.output]

noncomputable def overlayInTime (H : BaseTable) {n d : Nat} (hd : 0 < d)
    (t : PortTables.Table n d) :
    StateTransition.EvalsToInTime (TM2.step (program H d hd))
      ⟨some overlayEntry, clean H d hd, familyTapes H t⟩
      (some ⟨none, clean H d hd, finalTapes H t⟩)
      ((MachineOverlayTable.timePolynomial d overlayDegree).eval
        ((PortTables.tableBits (padded t)).length + (rotor H n).length)) := by
  let f := MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H ()
  have original := MachineOverlayTable.tableInTime d overlayDegree hd overlayDegree_positive
    (padded t) (PreprocessingStageMaps.familyAt H n) ()
  have framed := MachineStateFrame.frameExecution
    (MachineOverlayTable.program d overlayDegree hd overlayDegree_positive)
    ((f, false), (none : Option Bool))
    original
  have transported := MachineStateEquiv.execution (overlayStates d)
    (MachineStateFrame.frameProgram
      (MachineOverlayTable.program d overlayDegree hd overlayDegree_positive)) framed
  have sourceRun : StateTransition.EvalsToInTime (TM2.step (overlaySource d hd))
      ⟨some (.inl .copyFirst), clean H d hd,
        MachineOverlayTable.initialTapes (PortTables.tableBits (padded t)) (rotor H n)⟩
      (some ⟨none, clean H d hd,
        MachineOverlayTable.memory (PortTables.tableBits (padded t)) (rotor H n)
          [] [] [] [] [] [] []
          (PortTables.tableBits (PreprocessingStageMaps.paddedOverlay H d ⟨n, t⟩).2)⟩)
      ((MachineOverlayTable.timePolynomial d overlayDegree).eval
        ((PortTables.tableBits (padded t)).length + (rotor H n).length)) := by
    simpa only [overlaySource, MachineStateEquiv.configuration,
      MachineStateFrame.frameConfiguration, Option.map_some, overlayStates, Equiv.coe_fn_mk, clean, f,
      rotor_familyAt, PreprocessingStageMaps.paddedOverlay, PreprocessingStageMaps.padding,
      padded] using transported
  have run := placeExecution_inline_MachinePaddedOverlay overlayTape overlayView overlayView_left overlayView_right
    overlayLabel none (familyTapes H t) (overlaySource d hd) (program H d hd)
    (fun _ => rfl) sourceRun
  simpa only [Placement.configuration, Placement.label, familyTapes, finalTapes,
    MachineOverlayTable.initialTapes_memory, overlay_memory, overlayEntry] using run

noncomputable def sizePolynomial : Polynomial Nat :=
  Polynomial.C ExpanderFamily.growth * (Polynomial.X + 1)

noncomputable def archivePolynomial (d : Nat) : Polynomial Nat :=
  let s := sizePolynomial
  s + s * Polynomial.C d + 2 +
    (s * Polynomial.C d) * (s + s * Polynomial.C d + 8192) +
    (s * Polynomial.C overlayDegree) * (s * Polynomial.C overlayDegree + 1)

theorem archive_length_le (H : BaseTable) {n d : Nat} (t : PortTables.Table n d) :
    (PortTables.tableBits (padded t)).length + (rotor H n).length ≤
      (archivePolynomial d).eval (PortTables.tableBits t).length := by
  let m := PreprocessingLevels.paddedSize n
  let s := ExpanderFamily.growth * ((PortTables.tableBits t).length + 1)
  have hm : m ≤ s := MachineVertexPadding.power_length_bound t
  have hmd : m*d ≤ s*d := Nat.mul_le_mul_right d hm
  have hmq : m*overlayDegree ≤ s*overlayDegree := Nat.mul_le_mul_right overlayDegree hm
  have hg := GraphTables.tableBits_length_le (PortTables.graphTable (padded t))
  change (PortTables.tableBits (padded t)).length ≤
    m + m*d + 2 + m*d*(m + m*d + 8192) at hg
  have hg' := hg.trans (Nat.add_le_add
    (Nat.add_le_add_right (Nat.add_le_add hm hmd) 2)
    (Nat.mul_le_mul hmd (Nat.add_le_add_right (Nat.add_le_add hm hmd) 8192)))
  have hr := ExpanderTableWords.encode_rotationWords_length_le
    (PreprocessingStageMaps.familyAt H n)
  change (MachineOverlayTable.rawExpander (PreprocessingStageMaps.familyAt H n)).length ≤
    (m*overlayDegree)*(m*overlayDegree+1) at hr
  rw [rotor_familyAt] at hr
  have hr' := hr.trans (Nat.mul_le_mul hmq (Nat.add_le_add_right hmq 1))
  have h := Nat.add_le_add hg' hr'
  simpa only [archivePolynomial, sizePolynomial, Polynomial.eval_add, Polynomial.eval_mul,
    Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_one, Polynomial.eval_ofNat,
    s] using h

noncomputable def familyPolynomial : Polynomial Nat :=
  Polynomial.C MachineExpanderFamilyBounds.inputCoefficient * (Polynomial.X + 1)^5

noncomputable def timePolynomial (d : Nat) : Polynomial Nat :=
  MachineVertexPadding.timePolynomial d + familyPolynomial +
    (MachineOverlayTable.timePolynomial d overlayDegree).comp (archivePolynomial d)

noncomputable def execution (H : BaseTable) {n d : Nat} (hd : 0 < d)
    (t : PortTables.Table n d) :
    StateTransition.EvalsToInTime (TM2.step (program H d hd))
      ⟨some main, clean H d hd, initialTapes t⟩
      (some ⟨none, clean H d hd, finalTapes H t⟩)
      ((timePolynomial d).eval (PortTables.tableBits t).length) := by
  let first := paddingInTime H hd t
  let second := familyInTime H hd t
  let third := overlayInTime H hd t
  let firstTwo := StateTransition.EvalsToInTime.trans (TM2.step (program H d hd))
    _ _ _ _ _ first second
  let all := StateTransition.EvalsToInTime.trans (TM2.step (program H d hd))
    _ _ _ _ _ firstTwo third
  refine { toEvalsTo := all.toEvalsTo, steps_le_m := all.steps_le_m.trans ?_ }
  have hn := PortTables.vertices_le_tableBits_length t
  have hf := Nat.mul_le_mul_left MachineExpanderFamilyBounds.inputCoefficient
    (Nat.pow_le_pow_left (Nat.add_le_add_right hn 1) 5)
  have ho := natPolynomial_eval_mono (MachineOverlayTable.timePolynomial d overlayDegree)
    (archive_length_le H t)
  have h := Nat.add_le_add
    (Nat.add_le_add (Nat.le_refl ((MachineVertexPadding.timePolynomial d).eval
      (PortTables.tableBits t).length)) hf) ho
  simpa only [timePolynomial, familyPolynomial, Polynomial.eval_add, Polynomial.eval_comp,
    Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_X,
    Polynomial.eval_one, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using h

def machine (H : BaseTable) (d : Nat) (hd : 0 < d) : FinTM2 where
  K := Tape
  k₀ := .inl .original
  k₁ := .inr (.inr MachineOverlayTable.output)
  Γ := Alphabet
  Λ := Label d
  main := main
  σ := State d
  initialState := clean H d hd
  m := program H d hd

theorem alphabet_finite (H : BaseTable) (d : Nat) (hd : 0 < d) :
    ∀ k, Finite ((machine H d hd).Γ k) := by
  intro k
  change Finite Bool
  infer_instance

theorem initial_configuration (H : BaseTable) {n d : Nat} (hd : 0 < d)
    (t : PortTables.Table n d) :
    initList (machine H d hd) (PortTables.tableBits t) =
      ⟨some main, clean H d hd, initialTapes t⟩ := by
  have ht : (initList (machine H d hd) (PortTables.tableBits t)).stk = initialTapes t := by
    funext k
    rcases k with k | k
    · cases k <;> simp [initList, machine, initialTapes, memory, MachineVertexPadding.memory]
      rfl
    · rcases k with k | k
      · rcases k with k | k
        · rcases k with k | k <;> cases k <;>
            simp [initList, machine, initialTapes, memory]
        · cases k <;> simp [initList, machine, initialTapes, memory]
      · simp [initList, machine, initialTapes, memory]
  exact congrArg (TM2.Cfg.mk _ _) ht

theorem final_output (H : BaseTable) {n d : Nat} (hd : 0 < d)
    (t : PortTables.Table n d) :
    finalTapes H t (machine H d hd).k₁ =
      PortTables.inputBits (PreprocessingStageMaps.paddedOverlay H d ⟨n, t⟩) := by
  simp [finalTapes, machine, memory, PortTables.inputBits]

theorem original_preserved (H : BaseTable) {n d : Nat} (t : PortTables.Table n d) :
    finalTapes H t (.inl .original) = PortTables.tableBits t := rfl

end DFVSGames.Foundations.Complexity.MachinePaddedOverlay
end

section

namespace DFVSGames.Foundations.Complexity.MachinePaddedOverlayRuntime

open Turing
open PCP
open MachinePaddedOverlay (BaseTable Tape Label State)

def rawProgram (H : BaseTable) (d : Nat) (hd : 0 < d) :
    MachineCanonicalOutput.Program Tape (Label d) (State d) where
  input := .inl .original
  output := .inr (.inr MachineOverlayTable.output)
  main := MachinePaddedOverlay.main
  initial := MachinePaddedOverlay.clean H d hd
  code := MachinePaddedOverlay.program H d hd

theorem sourceMachine_eq (H : BaseTable) (d : Nat) (hd : 0 < d) :
    MachineCanonicalOutput.sourceMachine (rawProgram H d hd) =
      MachinePaddedOverlay.machine H d hd := rfl

noncomputable def cleanupTapes : List Tape :=
  (Finset.univ.erase (.inr (.inr MachineOverlayTable.output) : Tape)).toList

theorem cleanup_complete (H : BaseTable) (d : Nat) (hd : 0 < d) (k : Tape) :
    k ∈ cleanupTapes ↔ k ≠ (rawProgram H d hd).output := by
  simp [cleanupTapes, rawProgram]

theorem initial_configuration (H : BaseTable) (d : Nat) (hd : 0 < d)
    (a : PortTables.Input d) :
    initList (MachineCanonicalOutput.sourceMachine (rawProgram H d hd))
        (PortTables.inputBits a) =
      ⟨some MachinePaddedOverlay.main, MachinePaddedOverlay.clean H d hd,
        MachinePaddedOverlay.initialTapes a.2⟩ := by
  change initList (MachinePaddedOverlay.machine H d hd) (PortTables.tableBits a.2) = _
  exact MachinePaddedOverlay.initial_configuration H hd a.2

noncomputable def terminalRun (H : BaseTable) (d : Nat) (hd : 0 < d)
    (a : PortTables.Input d) :
    MachineCanonicalOutput.TerminalRun (rawProgram H d hd) (PortTables.inputBits a)
      (PortTables.inputBits (PreprocessingStageMaps.paddedOverlay H d a))
      ((MachinePaddedOverlay.timePolynomial d).eval (PortTables.inputBits a).length) where
  state := MachinePaddedOverlay.clean H d hd
  tapes := MachinePaddedOverlay.finalTapes H a.2
  execution := by
    rw [initial_configuration]
    exact MachinePaddedOverlay.execution H hd a.2
  output_eq := MachinePaddedOverlay.final_output H hd a.2

noncomputable def computableInPolyTime (H : BaseTable) (d : Nat) (hd : 0 < d) :
    TM2ComputableInPolyTime (PortTables.inputBits (ports := d))
      (PortTables.inputBits (ports := d + MachinePaddedOverlay.overlayDegree))
      (PreprocessingStageMaps.paddedOverlay H d) :=
  MachineCanonicalOutput.computableInPolyTime (rawProgram H d hd) cleanupTapes
    (cleanup_complete H d hd) PortTables.inputBits PortTables.inputBits
    (PreprocessingStageMaps.paddedOverlay H d) (MachinePaddedOverlay.timePolynomial d)
    (terminalRun H d hd)

theorem finite_alphabet (H : BaseTable) (d : Nat) (hd : 0 < d) :
    ∀ k, Finite ((computableInPolyTime H d hd).tm.Γ k) :=
  MachineCanonicalOutput.computableInPolyTime_finite_alphabet (rawProgram H d hd) cleanupTapes
    (cleanup_complete H d hd) PortTables.inputBits PortTables.inputBits
    (PreprocessingStageMaps.paddedOverlay H d) (MachinePaddedOverlay.timePolynomial d)
    (terminalRun H d hd)

end DFVSGames.Foundations.Complexity.MachinePaddedOverlayRuntime
end

section

namespace DFVSGames.Foundations.Complexity.MachineLazyCodec
open PCP.GraphTables PCP.PreprocessingLazyWords

theorem rowsBits_ofFn (v e count : Nat) :
    MachineDummyRows.rowsBits v e count =
      (List.ofFn fun p : Fin count => MachineDummyRows.rowBits v (e + p.val)).flatten := by
  induction count generalizing e with
  | zero => rfl
  | succ count ih =>
    rw [MachineDummyRows.rowsBits, List.ofFn_succ, List.flatten_cons]
    simp only [Fin.val_zero, Nat.add_zero]
    apply congrArg (MachineDummyRows.rowBits v e ++ ·)
    rw [ih]
    apply congrArg List.flatten
    congr 1
    funext p
    simp only [Fin.val_succ]
    congr 1
    omega

private theorem encodeWords_flatMap_inline_MachineLazyCodec {α : Type*} (items : List α) (words : α → List Nat) :
    encodeWords (items.flatMap words) = items.flatMap (fun x => encodeWords (words x)) := by
  induction items with
  | nil => rfl
  | cons item items ih => simp only [List.flatMap_cons, encodeWords_append, ih]

theorem rowBits_stay {n d : Nat} (v : Fin n) (p : Fin d) :
    MachineDummyRows.rowBits v.val (2 * d * v.val + p.val) =
      encodeWords (rowWords (stayRow d v p)) := by
  have h := MachineDummyRows.rowBits_eq_graph_row v (stayRow d v p).reverseIndex
  rw [stayRow_reverse_val] at h
  exact h

theorem rowsBits_stay {n d : Nat} (v : Fin n) :
    MachineDummyRows.rowsBits v.val (2 * d * v.val) d =
      encodeWords ((List.ofFn (stayRow d v)).flatMap rowWords) := by
  rw [rowsBits_ofFn, encodeWords_flatMap_inline_MachineLazyCodec]
  simp only [List.flatMap_def, List.map_ofFn]
  apply congrArg List.flatten
  congr 1
  funext p
  exact rowBits_stay v p

end DFVSGames.Foundations.Complexity.MachineLazyCodec
end

end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end
end

end OAI