File size: 25,218 Bytes
760f90e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import Mathlib.Algebra.BigOperators.Field
import OAI.Computability.UniqueGames.Decoding.AdviceFibersLemmas
import OAI.Computability.UniqueGames.Decoding.DimensionSelection
import OAI.Computability.UniqueGames.Decoding.MatrixCoordinates
import OAI.Computability.UniqueGames.Decoding.PrivateStrategyLemmas
import OAI.Computability.UniqueGames.Decoding.SparseLawLemmas
import OAI.Computability.UniqueGames.Decoding.TableKeysGame
import OAI.Computability.UniqueGames.Foundations.SamplingLemmas
import OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridEnergyLemmas
import OAI.Computability.UniqueGames.Inverse.RowErasureMatrixLemmas
import OAI.Computability.UniqueGames.Reduction.ActualSourceLemmas

namespace OAI

section

noncomputable section
open scoped BigOperators Classical
open UniqueGamesTheorem.Integration.BinaryLinear
open UniqueGamesTheorem.Reduction UniqueGamesTheorem.Reduction.ActualSource
open UniqueGamesTheorem.Fourier.MatrixNoise

namespace UniqueGamesTheorem.Decoder.ActualSpectral

open TableKeysGame PositiveMultiplier NoiseSampler SurrogateFibers

local instance homFintype {D F : Type*}
    [AddCommGroup D] [Module F2 D] [AddCommGroup F] [Module F2 F]
    [Fintype D] [Fintype F] : Fintype (D →ₗ[F2] F) :=
  Fintype.ofInjective (fun M : D →ₗ[F2] F => (M : D → F)) DFunLike.coe_injective

theorem expect_prod {A B : Type*} [Fintype A] [Fintype B] (f : A × B → ℝ) :
    (𝔼 p, f p) = 𝔼 a, 𝔼 b, f (a, b) := by
  simpa only [Finset.univ_product_univ] using
    (Finset.expect_product Finset.univ Finset.univ f)

theorem expect_eq_uniform_sum {I : Type*} [Fintype I] (f : I → ℝ) :
    (𝔼 i, f i) = ∑ i, (Fintype.card I : ℝ)⁻¹ * f i := by
  rw [Fintype.expect_eq_sum_div_card, ← Finset.mul_sum]
  ring

/-- The finite noise law's multiplier is exactly the rational kernel event
of the same gadget, cast to the real numbers. -/
theorem eigenvalue_eq_kernelProbability {s d : Nat} (g : SplitGadget s d)
    {P : Type} [AddCommGroup P] [Module F2 P] (S : Ambient s d →ₗ[F2] P) :
    linearNoiseEigenvalue (samplerLaw g.noise) S =
      (Integration.SplitGadget.kernelProbability g S : ℝ) := by
  rw [← sample_kernel_eq_eigenvalue]
  unfold Integration.SplitGadget.kernelProbability
  rw [rat_expect_cast]
  simp only [apply_ite, Rat.cast_one, Rat.cast_zero]

/-- The four independent samples of the actual single-orbit test. -/
theorem acceptance_nested (S : Source) (k : Nat) {s d : Nat}
    (g : SplitGadget s d) (label : Fin (vertexCount S k s d) → Fin (2 ^ s)) :
    (acceptanceProbability S k g label : ℝ) =
      𝔼 U : Question S k, 𝔼 X : Map k s d, 𝔼 i : g.NoiseIndex, 𝔼 l : Dual k,
        if unfolded S k s d label (U, X) =
          unfolded S k s d label (U, X + l.smulRight (g.noise i))
        then (1 : ℝ) else 0 := by
  rw [acceptanceProbability_eq_test, rat_expect_cast]
  simp only [apply_ite, Rat.cast_one, Rat.cast_zero]
  simp only [expect_prod, leftQuery, rightQuery, ActualGame.leftQuery, ActualGame.rightQuery]
  apply Finset.expect_congr rfl
  intro U _
  apply Finset.expect_congr rfl
  intro X _
  apply Finset.expect_congr rfl
  intro i _
  apply Finset.expect_congr rfl
  intro l _
  by_cases h : unfolded S k s d label (U, X) =
      unfolded S k s d label (U, X + l.smulRight (g.noise i)) <;> simp [h]

/-- No auxiliary side labeling is introduced: the same restored table occurs
on both sides of the actual equality test. -/
theorem acceptance_eq_equality_mean (S : Source) (k : Nat) {s d : Nat}
    (g : SplitGadget s d) (label : Fin (vertexCount S k s d) → Fin (2 ^ s)) :
    (acceptanceProbability S k g label : ℝ) =
      𝔼 U : Question S k,
        equalityAcceptance (samplerLaw g.noise) (fun X : Map k s d =>
          unfolded S k s d label (U, X)) := by
  rw [acceptance_nested]
  apply Finset.expect_congr rfl
  intro U _
  unfold equalityAcceptance
  apply Finset.expect_congr rfl
  intro X _
  rw [← sample_expect_eq]
  apply Finset.expect_congr rfl
  intro i _
  apply Finset.expect_congr rfl
  intro l _
  split_ifs <;> rfl

def fiberAcceptance (S : Source) (k s d : Nat)
    (label : Fin (vertexCount S k s d) → Fin (2 ^ s))
    (U : Question S k) (T : ActualHomogeneous.E k →ₗ[F2] Vector d) : ℝ :=
  shortcodeAcceptance (fun M : ActualHomogeneous.E k →ₗ[F2] Alphabet s =>
    unfolded S k s d label (U, M.prod T))

theorem fiberAcceptance_le_one (S : Source) (k s d : Nat)
    (label : Fin (vertexCount S k s d) → Fin (2 ^ s))
    (U : Question S k) (T : ActualHomogeneous.E k →ₗ[F2] Vector d) :
    fiberAcceptance S k s d label U T ≤ 1 := by
  unfold fiberAcceptance shortcodeAcceptance
  apply Finset.expect_le Finset.univ_nonempty
  intro M _
  apply Finset.expect_le Finset.univ_nonempty
  intro a _
  apply Finset.expect_le Finset.univ_nonempty
  intro l _
  split_ifs <;> norm_num

theorem weighted_fiber_mean_lower (S : Source) (k : Nat) {s d : Nat}
    (g : SplitGadget s d) (label : Fin (vertexCount S k s d) → Fin (2 ^ s))
    (μ : Question S k → ℝ) (r : Nat)
    (hμ : ∀ U, 0 ≤ μ U) (hμsum : ∑ U, μ U = 1)
    (hkernel : ∀ L : Ambient s d →ₗ[F2] ActualHomogeneous.E k,
      r ≤ Module.finrank F2 (L.comp (alphabetEmbedding s d)).range →
      Integration.SplitGadget.kernelProbability g L ≤ 7 / 8)
    (haccept : (99 : ℝ) / 100 ≤ ∑ U, μ U *
      equalityAcceptance (samplerLaw g.noise)
        (fun X : Map k s d => unfolded S k s d label (U, X))) :
    (9 : ℝ) / 10 * ((2 : ℝ) ^ r)⁻¹ ≤
      ∑ U, μ U * (𝔼 T, fiberAcceptance S k s d label U T) := by
  have h := matrix_spectral_comparison μ (samplerLaw g.noise) (alphabetEmbedding s d)
    (fun U (X : Map k s d) => unfolded S k s d label (U, X)) r
    hμ hμsum (samplerLaw_nonneg g.noise) (samplerLaw_normalized g.noise)
    (fun L hL => by
      rw [eigenvalue_eq_kernelProbability]
      have hc := (Rat.cast_le (K := ℝ)).mpr (hkernel L hL)
      simpa only [Rat.cast_div, Rat.cast_ofNat] using hc) haccept
  simpa only [alphabetEmbedding, surrogate_acceptance_eq_fiber_average,
    fiberAcceptance] using h

theorem actual_fiber_mean_lower (S : Source) (k : Nat) {s d : Nat}
    (g : SplitGadget s d) (label : Fin (vertexCount S k s d) → Fin (2 ^ s)) (r : Nat)
    (hkernel : ∀ L : Ambient s d →ₗ[F2] ActualHomogeneous.E k,
      r ≤ Module.finrank F2 (L.comp (alphabetEmbedding s d)).range →
      Integration.SplitGadget.kernelProbability g L ≤ 7 / 8)
    (haccept : (99 : ℚ) / 100 ≤ acceptanceProbability S k g label) :
    (9 : ℝ) / 10 * ((2 : ℝ) ^ r)⁻¹ ≤
      𝔼 U : Question S k, 𝔼 T, fiberAcceptance S k s d label U T := by
  rw [expect_eq_uniform_sum]
  apply weighted_fiber_mean_lower S k g label
    (fun _ => (Fintype.card (Question S k) : ℝ)⁻¹) r
  · intro U
    positivity
  · rw [Finset.sum_const, Finset.card_univ, nsmul_eq_mul]
    apply mul_inv_cancel₀
    exact_mod_cast Fintype.card_ne_zero (α := Question S k)
  · exact hkernel
  · have hc := (Rat.cast_le (K := ℝ)).mpr haccept
    rw [acceptance_eq_equality_mean, expect_eq_uniform_sum] at hc
    simpa only [Rat.cast_div, Rat.cast_ofNat] using hc

def eta (r : Nat) : ℝ := ((2 : ℝ) ^ r)⁻¹ / 16

theorem eta_pos (r : Nat) : 0 < eta r := by unfold eta; positivity

/-- At least `10 η` of the actual `(U,T)` pairs have shortcode acceptance
at least `4 η`, exactly the input needed by row erasure. -/
theorem actual_good_fiber_mass (S : Source) (k : Nat) {s d : Nat}
    (g : SplitGadget s d) (label : Fin (vertexCount S k s d) → Fin (2 ^ s)) (r : Nat)
    (hkernel : ∀ L : Ambient s d →ₗ[F2] ActualHomogeneous.E k,
      r ≤ Module.finrank F2 (L.comp (alphabetEmbedding s d)).range →
      Integration.SplitGadget.kernelProbability g L ≤ 7 / 8)
    (haccept : (99 : ℚ) / 100 ≤ acceptanceProbability S k g label) :
    10 * eta r ≤ 𝔼 U : Question S k,
      𝔼 T : ActualHomogeneous.E k →ₗ[F2] Vector d,
        if 4 * eta r ≤ fiberAcceptance S k s d label U T then (1 : ℝ) else 0 := by
  let I := Question S k × (ActualHomogeneous.E k →ₗ[F2] Vector d)
  let μ : I → ℝ := fun _ => (Fintype.card I : ℝ)⁻¹
  let p : I → ℝ := fun a => fiberAcceptance S k s d label a.1 a.2
  have hmean := actual_fiber_mean_lower S k g label r hkernel haccept
  have hmean' : (72 : ℝ) / 5 * eta r ≤ ∑ a, μ a * p a := by
    rw [← expect_eq_uniform_sum, expect_prod]
    unfold eta
    nlinarith
  have h := good_fiber_mass μ p (eta r) (fun _ => by positivity)
    (by simp [μ, Fintype.card_ne_zero]) (eta_pos r).le
    (fun a => fiberAcceptance_le_one S k s d label a.1 a.2) hmean'
  change 10 * eta r ≤
    ∑ a : Question S k × (ActualHomogeneous.E k →ₗ[F2] Vector d),
      (Fintype.card (Question S k × (ActualHomogeneous.E k →ₗ[F2] Vector d)) : ℝ)⁻¹ *
        (if 4 * eta r ≤ fiberAcceptance S k s d label a.1 a.2 then 1 else 0) at h
  rw [← expect_eq_uniform_sum, expect_prod] at h
  exact h

end UniqueGamesTheorem.Decoder.ActualSpectral

end

end

section

namespace UniqueGamesTheorem.Decoder.ActualGoodRows

open Integration.BinaryLinear Reduction ActualSource
open Inverse Inverse.RowErasure
open Inverse.Shortcode (Mat HasAffineSlice)
open scoped BigOperators Classical

noncomputable section

local instance homFintype {D F : Type*}
    [AddCommGroup D] [Module F2 D] [AddCommGroup F] [Module F2 F]
    [Fintype D] [Fintype F] : Fintype (D →ₗ[F2] F) :=
  Fintype.ofInjective (fun M : D →ₗ[F2] F => (M : D → F)) DFunLike.coe_injective

def table (S : Source) (k s d : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s))
    (U : ActualGame.Question S k) (T : ActualHomogeneous.E k →ₗ[F2] Vector d)
    (M : Mat s (1 + 2 * k)) : Vector s :=
  TableKeysGame.unfolded S k s d labeling
    (U, ((MatrixCoordinates.mapEquiv k s).symm M).prod T)

theorem table_acceptance (S : Source) (k s d : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s))
    (U : ActualGame.Question S k) (T : ActualHomogeneous.E k →ₗ[F2] Vector d) :
    Shortcode.equalityAcceptance (table S k s d labeling U T) =
      ActualSpectral.fiberAcceptance S k s d labeling U T := by
  unfold table
  rw [← MatrixCoordinates.shortcodeAcceptance_eq k s
    (fun M : ActualHomogeneous.E k →ₗ[F2] Vector s =>
      TableKeysGame.unfolded S k s d labeling (U, M.prod T))]
  unfold ActualSpectral.fiberAcceptance SurrogateFibers.shortcodeAcceptance
  apply Finset.expect_congr (by ext M; simp only [Finset.mem_univ])
  intro M _
  apply Finset.expect_congr (by ext a; simp only [Finset.mem_univ])
  intro a _
  apply Finset.expect_congr (by ext l; simp only [Finset.mem_univ])
  intro l _
  rfl

/-- The row-advice probability in actual matrix coordinates. In particular,
dependent rows of `A` are sampled with their full multiplicity. -/
def adviceMass (S : Source) (k s d r : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s)) (α : ℝ) : ℝ :=
  𝔼 U : ActualGame.Question S k,
    𝔼 T : ActualHomogeneous.E k →ₗ[F2] Vector d,
      RowErasure.adviceMass
        ((RowErasureMatrix.family s (1 + 2 * k) r).goodAt (table S k s d labeling U T) α)

def goodRowMass (rstar s r : ℕ) : ℝ :=
  10 * ActualSpectral.eta rstar ^ 2 / (2 : ℝ) ^ (s * r)

theorem goodRowMass_pos (rstar s r : ℕ) : 0 < goodRowMass rstar s r := by
  unfold goodRowMass
  have h := ActualSpectral.eta_pos rstar
  positivity

theorem exists_actual_advice_threshold (rstar : ℕ) (α : ℝ)
    (hα : 0 < α) (hαone : α ≤ 1) (s r : ℕ)
    (hr : r < s) (halphabet : 1 / (2 : ℝ) ^ s ≤ α / 8) :
    ∃ k₀ : ℕ, ∀ k : ℕ, k₀ ≤ k →
      (∀ f : Mat s (1 + 2 * k) → Vector s,
        ActualSpectral.eta rstar ≤ Shortcode.equalityAcceptance f → HasAffineSlice f α r) →
      ∀ (S : Source) (d : ℕ) (g : SplitGadget s d)
        (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s)),
        (∀ L : Ambient s d →ₗ[F2] ActualHomogeneous.E k,
          rstar ≤ Module.finrank F2 (L.comp (alphabetEmbedding s d)).range →
          Integration.SplitGadget.kernelProbability g L ≤ 7 / 8) →
        (99 : ℚ) / 100 ≤ TableKeysGame.acceptanceProbability S k g labeling →
        goodRowMass rstar s r ≤ adviceMass S k s d r labeling α := by
  obtain ⟨m₀, hm₀⟩ := RowErasureMatrix.exists_contextual_advice_threshold
    (ActualSpectral.eta rstar) α (ActualSpectral.eta_pos rstar) hα hαone
    s r hr halphabet
  refine ⟨m₀, ?_⟩
  intro k hk hinverse S d g labeling hkernel haccept
  let Q := ActualGame.Question S k × (ActualHomogeneous.E k →ₗ[F2] Vector d)
  let f : Q → Mat s (1 + 2 * k) → Vector s :=
    fun q => table S k s d labeling q.1 q.2
  have hcontext : 10 * ActualSpectral.eta rstar ≤
      uniformMass (fun q : Q => 4 * ActualSpectral.eta rstar ≤
        Shortcode.equalityAcceptance (f q)) := by
    have h := ActualSpectral.actual_good_fiber_mass S k g labeling rstar hkernel haccept
    dsimp only [Q, f]
    unfold uniformMass
    rw [ActualSpectral.expect_prod]
    simpa only [indicator, table_acceptance] using h
  have h := hm₀ (1 + 2 * k) (by omega) hinverse Q f hcontext
  dsimp only [Q, f] at h
  rw [ActualSpectral.expect_prod] at h
  simpa only [goodRowMass, adviceMass] using h

end
end UniqueGamesTheorem.Decoder.ActualGoodRows

end

section

/-! The two full-table events used in the projected-witness transfer. Their
sample space contains actual occurrence tuples and complete affine tables,
but no projection choice. The selected witness depends on row advice only.
-/

namespace UniqueGamesTheorem.Decoder.ActualEvents

open Integration.BinaryLinear Reduction ActualSource Foundations.Games
open Inverse Inverse.RowErasure
open Inverse.Shortcode (Mat)
open scoped BigOperators Classical

noncomputable section

local instance homFintype {D F : Type*}
    [AddCommGroup D] [Module F2 D] [AddCommGroup F] [Module F2 F]
    [Fintype D] [Fintype F] : Fintype (D →ₗ[F2] F) :=
  Fintype.ofInjective (fun M : D →ₗ[F2] F => (M : D → F)) DFunLike.coe_injective

abbrev Context (S : Source) (k d : ℕ) :=
  ActualGame.Question S k × (ActualHomogeneous.E k →ₗ[F2] Vector d)

abbrev Sample (S : Source) (k s d r : ℕ) :=
  Context S k d × (RowErasureDescriptions.RowMap s r × Mat s (1 + 2 * k))

abbrev FullTableSample (S : Source) (k s d r : ℕ) :=
  (ActualGame.Question S k × (Alphabet s →ₗ[F2] Vector r)) × ActualGame.Map k s d

/-- A bijection merely rearranges the full sampled table and changes its
matrix coordinates. It never appends the hidden projection to this law. -/
def fullTableEquiv (S : Source) (k s d r : ℕ) :
    FullTableSample S k s d r ≃ Sample S k s d r where
  toFun p := ((p.1.1, (LinearMap.snd F2 (Alphabet s) (Vector d)).comp p.2),
    (LinearMap.toMatrix' p.1.2,
      MatrixCoordinates.mapEquiv k s ((LinearMap.fst F2 (Alphabet s) (Vector d)).comp p.2)))
  invFun q := ((q.1.1, Matrix.toLin' q.2.1),
    ((MatrixCoordinates.mapEquiv k s).symm q.2.2).prod q.1.2)
  left_inv p := by
    rcases p with ⟨⟨U, A⟩, P⟩
    apply Prod.ext
    · simp
    · apply LinearMap.ext
      intro x
      simp only [LinearEquiv.symm_apply_apply, LinearMap.prod_apply]
      rfl
  right_inv q := by
    rcases q with ⟨⟨U, T⟩, A, M⟩
    apply Prod.ext
    · apply Prod.ext rfl
      apply LinearMap.ext
      intro x
      rfl
    · apply Prod.ext
      · exact LinearMap.toMatrix'_toLin' A
      · change MatrixCoordinates.mapEquiv k s
          ((LinearMap.fst F2 (Alphabet s) (Vector d)).comp
            (((MatrixCoordinates.mapEquiv k s).symm M).prod T)) = M
        have hf : (LinearMap.fst F2 (Alphabet s) (Vector d)).comp
            (((MatrixCoordinates.mapEquiv k s).symm M).prod T) =
              (MatrixCoordinates.mapEquiv k s).symm M := by
          apply LinearMap.ext
          intro x
          rfl
        rw [hf, LinearEquiv.apply_symm_apply]

def unrestricted (S : Source) (k s d r : ℕ) : FiniteDistribution (Sample S k s d r) :=
  FiniteDistribution.uniform _

def sliceEvent (S : Source) (k s d r : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s))
    (α : ℝ) (p : Sample S k s d r) : Bool :=
  decide ((RowErasureMatrix.family s (1 + 2 * k) r).selectedEvent
    (ActualGoodRows.table S k s d labeling p.1.1 p.1.2) α p.2.1 p.2.2)

def targetHit (S : Source) (k s d r : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s))
    (α : ℝ) (p : Sample S k s d r) : Bool :=
  decide ((RowErasureMatrix.family s (1 + 2 * k) r).selectedMatch
    (ActualGoodRows.table S k s d labeling p.1.1 p.1.2) α p.2.1 p.2.2)

theorem targetHit_implies_slice (S : Source) (k s d r : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s))
    (α : ℝ) (p : Sample S k s d r)
    (h : targetHit S k s d r labeling α p = true) :
    sliceEvent S k s d r labeling α p = true := by
  exact of_decide_eq_true h |> fun hm => decide_eq_true
    ((RowErasureMatrix.family s (1 + 2 * k) r).selectedMatch_event _ α _ _ hm)

theorem uniform_probability_expect {Ω : Type*} [Fintype Ω] [Nonempty Ω]
    (p : Ω → Bool) :
    (FiniteDistribution.uniform Ω).probability p =
      𝔼 x : Ω, if p x then (1 : ℝ) else 0 := by
  simp only [FiniteDistribution.probability, FiniteDistribution.uniform,
    Fintype.expect_eq_sum_div_card, Finset.sum_div, ite_div, one_div, zero_div]

theorem unrestricted_slice_mass (S : Source) (k s d r : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s)) (α : ℝ) :
    (unrestricted S k s d r).probability (sliceEvent S k s d r labeling α) =
      𝔼 q : Context S k d,
        RowErasureMatrix.selectedEventMass r
          (ActualGoodRows.table S k s d labeling q.1 q.2) α := by
  unfold unrestricted
  rw [uniform_probability_expect, ActualSpectral.expect_prod]
  apply Finset.expect_congr rfl
  intro q _
  rw [ActualSpectral.expect_prod]
  simp only [sliceEvent, RowErasureMatrix.selectedEventMass, uniformMass, indicator,
    decide_eq_true_eq]

theorem unrestricted_match_mass (S : Source) (k s d r : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s)) (α : ℝ) :
    (unrestricted S k s d r).probability
      (fun p => sliceEvent S k s d r labeling α p && targetHit S k s d r labeling α p) =
      𝔼 q : Context S k d,
        RowErasureMatrix.selectedMatchMass r
          (ActualGoodRows.table S k s d labeling q.1 q.2) α := by
  have he : (fun p => sliceEvent S k s d r labeling α p && targetHit S k s d r labeling α p) =
      targetHit S k s d r labeling α := by
    funext p
    by_cases h : targetHit S k s d r labeling α p = true
    · simp [h, targetHit_implies_slice S k s d r labeling α p h]
    · simp [Bool.eq_false_iff.mpr h]
  rw [he]
  unfold unrestricted
  rw [uniform_probability_expect, ActualSpectral.expect_prod]
  apply Finset.expect_congr rfl
  intro q _
  rw [ActualSpectral.expect_prod]
  simp only [targetHit, RowErasureMatrix.selectedMatchMass, uniformMass, indicator,
    decide_eq_true_eq]

/-- The full-table slice event pays exactly one bounded column-fiber factor. -/
theorem slice_probability_lower (S : Source) (k s d r : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s)) (α g₀ : ℝ)
    (hgood : g₀ ≤ ActualGoodRows.adviceMass S k s d r labeling α) :
    g₀ * (1 / (2 : ℝ) ^ (s * r)) ≤
      (unrestricted S k s d r).probability (sliceEvent S k s d r labeling α) := by
  rw [unrestricted_slice_mass]
  have h := RowErasureMatrix.selectedEventMass_contextual_ge (r := r)
    (fun q : Context S k d => ActualGoodRows.table S k s d labeling q.1 q.2) α g₀
    (by simpa only [ActualGoodRows.adviceMass, ActualSpectral.expect_prod] using hgood)
  simpa only [mul_comm] using h

theorem target_probability_lower (S : Source) (k s d r : ℕ)
    (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s)) (α : ℝ) :
    (α / 2) * (unrestricted S k s d r).probability (sliceEvent S k s d r labeling α) ≤
      (unrestricted S k s d r).probability
        (fun p => sliceEvent S k s d r labeling α p && targetHit S k s d r labeling α p) := by
  rw [unrestricted_slice_mass, unrestricted_match_mass]
  exact RowErasureMatrix.selectedMatchMass_contextual_ge (r := r)
    (fun q : Context S k d => ActualGoodRows.table S k s d labeling q.1 q.2) α

end
end UniqueGamesTheorem.Decoder.ActualEvents

end

section

namespace UniqueGamesTheorem.Decoder.MatrixGapChoice

open Integration.BinaryLinear Reduction ActualSource
open Inverse.Shortcode (Mat HasAffineSlice InversePrinciple equalityAcceptance)

noncomputable section

/-- Fixed dimensions, density and sparse mask for one logical alphabet.
The remaining gadget codimension may be arbitrary when choosing the cube. -/
structure InverseParameters (rstar : ℕ) where
  α : ℝ
  positive : 0 < α
  bounded : α ≤ 1
  r : ℕ
  s : ℕ
  s_large : rstar ≤ s
  r_small : r < s
  trivial_small : 1 / (2 : ℝ) ^ (s - r) < α / 8
  tupleThreshold : ℕ
  inverse : ∀ k : ℕ, tupleThreshold ≤ k →
    ∀ f : Mat s (1 + 2 * k) → Vector s,
      ActualSpectral.eta rstar ≤ equalityAcceptance f → HasAffineSlice f α r
  advice : ∀ k : ℕ, tupleThreshold ≤ k →
    ∀ (S : Source) (d : ℕ) (g : SplitGadget s d)
      (labeling : Fin (TableKeysGame.vertexCount S k s d) → Fin (2 ^ s)),
      (∀ L : Ambient s d →ₗ[F2] ActualHomogeneous.E k,
        rstar ≤ Module.finrank F2 (L.comp (alphabetEmbedding s d)).range →
        Integration.SplitGadget.kernelProbability g L ≤ 7 / 8) →
      (99 : ℚ) / 100 ≤ TableKeysGame.acceptanceProbability S k g labeling →
      ActualGoodRows.goodRowMass rstar s r ≤ ActualGoodRows.adviceMass S k s d r labeling α

theorem eta_lt_one (rstar : ℕ) : ActualSpectral.eta rstar < 1 := by
  have hp : (1 : ℝ) ≤ 2 ^ rstar := one_le_pow₀ (by norm_num)
  have hi : 1 / (2 : ℝ) ^ rstar ≤ 1 := by
    exact (div_le_one (by positivity)).mpr hp
  unfold ActualSpectral.eta
  rw [← one_div]
  linarith

theorem exists_inverse_parameters (hinverse : InversePrinciple) (rstar : ℕ) :
    Nonempty (InverseParameters rstar) := by
  obtain ⟨α, hα, hαone, r, _hr, s₀, hinv⟩ :=
    hinverse (ActualSpectral.eta rstar) (ActualSpectral.eta_pos rstar) (eta_lt_one rstar)
  obtain ⟨s, hs, hrs, hsmall, _htiny⟩ := DimensionSelection.exists_logical_dimension
    hα (ActualSpectral.eta_pos rstar) r (max rstar s₀)
  have hsstar : rstar ≤ s := (le_max_left _ _).trans hs
  have hs₀ : s₀ ≤ s := (le_max_right _ _).trans hs
  obtain ⟨m₀, hm₀⟩ := hinv s hs₀
  have halphabet : 1 / (2 : ℝ) ^ s ≤ α / 8 := by
    have hp : (2 : ℝ) ^ (s - r) ≤ 2 ^ s :=
      pow_le_pow_right₀ (by norm_num) (Nat.sub_le s r)
    exact (one_div_le_one_div_of_le (by positivity) hp).trans hsmall.le
  obtain ⟨k₀, hk₀⟩ := ActualGoodRows.exists_actual_advice_threshold
    rstar α hα hαone s r hrs halphabet
  let threshold := max m₀ k₀
  have hi (k : ℕ) (hk : threshold ≤ k) :
      ∀ f : Mat s (1 + 2 * k) → Vector s,
        ActualSpectral.eta rstar ≤ equalityAcceptance f → HasAffineSlice f α r := by
    apply hm₀ (1 + 2 * k)
    have hm : m₀ ≤ k := (le_max_left _ _).trans hk
    omega
  refine ⟨{
    α := α
    positive := hα
    bounded := hαone
    r := r
    s := s
    s_large := hsstar
    r_small := hrs
    trivial_small := hsmall
    tupleThreshold := threshold
    inverse := hi
    advice := ?_ }⟩
  intro k hk S d g labeling hkernel haccept
  exact hk₀ k ((le_max_right _ _).trans hk) (hi k hk) S d g labeling hkernel haccept

/-- After all fixed dimensions are known, the cube simultaneously exceeds the
inverse threshold, reduces full-table variation, and beats the decoder mass. -/
theorem exists_cube {rstar : ℕ} (P : InverseParameters rstar) (d : ℕ) :
    ∃ m : ℕ, 0 < m ∧ P.tupleThreshold ≤ m ^ 3 ∧
      0 ≤ 1 / (m : ℝ) ^ 2 ∧ 1 / (m : ℝ) ^ 2 ≤ 1 ∧
      Foundations.Information.totalVariation
        (SparseLaw.independentWeights
          (SparseLaw.mixture (1 / (m : ℝ) ^ 2)
            (SparseLaw.singletonPairWeights (Ambient P.s d))) (m ^ 3))
        (SparseLaw.uniformWeights (Fin (m ^ 3) → Ambient P.s d × Ambient P.s d)) ≤
          ConstantSelection.variationBudget P.α (ActualGoodRows.goodRowMass rstar P.s P.r) P.s P.r ∧
      (1 - ((1 / (m : ℝ) ^ 2) / (2 : ℝ) ^ (d + P.r)) / 3600) ^ (m ^ 3) <
        ConstantSelection.decodingMass P.α (ActualGoodRows.goodRowMass rstar P.s P.r) P.s P.r := by
  obtain ⟨m, hlarge, hm, htv, hrate⟩ := ConstantSelection.exists_matrix_cube (Ambient P.s d)
    P.positive (ActualGoodRows.goodRowMass_pos rstar P.s P.r) P.s P.r d P.tupleThreshold
  have hmreal : (1 : ℝ) ≤ m := by exact_mod_cast (Nat.succ_le_iff.mpr hm)
  have hmsq : (1 : ℝ) ≤ (m : ℝ) ^ 2 := one_le_pow₀ hmreal
  refine ⟨m, hm, hlarge.trans (Nat.le_self_pow (by decide : (3 : ℕ) ≠ 0) m),
    by positivity, ?_, htv, hrate⟩
  exact (div_le_one (by positivity)).mpr hmsq

end
end UniqueGamesTheorem.Decoder.MatrixGapChoice

end

end OAI