roseking commited on
Commit
2f887db
·
verified ·
1 Parent(s): ea76aac

Add lean source and binary files (part 62)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lean/OAI/Computability/MinUncut/Estimates/RowListBridge.lean +63 -0
  2. lean/OAI/Computability/MinUncut/Estimates/SamplerAssembly.lean +93 -0
  3. lean/OAI/Computability/MinUncut/Estimates/SamplerCost.lean +106 -0
  4. lean/OAI/Computability/MinUncut/Estimates/SecondFailureIndicator.lean +259 -0
  5. lean/OAI/Computability/MinUncut/Estimates/SelectedProject.lean +59 -0
  6. lean/OAI/Computability/MinUncut/Estimates/SelectedProjectSliceContinuous.lean +53 -0
  7. lean/OAI/Computability/MinUncut/Estimates/SelectedSyntax.lean +57 -0
  8. lean/OAI/Computability/MinUncut/Estimates/SingleRow.lean +125 -0
  9. lean/OAI/Computability/MinUncut/Estimates/TM2Costed.lean +724 -0
  10. lean/OAI/Computability/MinUncut/Estimates/TableLawPacking.lean +92 -0
  11. lean/OAI/Computability/MinUncut/Estimates/TableTestFunctions.lean +101 -0
  12. lean/OAI/Computability/MinUncut/Estimates/TemplateExpressions.lean +376 -0
  13. lean/OAI/Computability/MinUncut/Estimates/UniformAlgebra.lean +90 -0
  14. lean/OAI/Computability/MinUncut/Estimates/UniformBoolean.lean +97 -0
  15. lean/OAI/Computability/MinUncut/Estimates/UniformEquation.lean +288 -0
  16. lean/OAI/Computability/MinUncut/Estimates/UniformEquationOutput.lean +298 -0
  17. lean/OAI/Computability/MinUncut/Estimates/UniformFaceArray.lean +36 -0
  18. lean/OAI/Computability/MinUncut/Estimates/UniformGrid.lean +483 -0
  19. lean/OAI/Computability/MinUncut/Estimates/UniformOutput.lean +27 -0
  20. lean/OAI/Computability/MinUncut/Estimates/UniformProduct.lean +65 -0
  21. lean/OAI/Computability/MinUncut/Estimates/UniformRestrict.lean +195 -0
  22. lean/OAI/Computability/MinUncut/Estimates/UniformSets.lean +59 -0
  23. lean/OAI/Computability/MinUncut/Estimates/UniformTransport.lean +119 -0
  24. lean/OAI/Computability/MinUncut/Estimates/WeightedTestLaw.lean +187 -0
  25. lean/OAI/Computability/MinUncut/Games/Actual.lean +688 -0
  26. lean/OAI/Computability/MinUncut/Games/AdaptiveKernel.lean +83 -0
  27. lean/OAI/Computability/MinUncut/Games/AffineLabels.lean +91 -0
  28. lean/OAI/Computability/MinUncut/Games/Basic.lean +684 -0
  29. lean/OAI/Computability/MinUncut/Games/FinalCNFHeader.lean +733 -0
  30. lean/OAI/Computability/MinUncut/Games/FinalCNFOutput.lean +406 -0
  31. lean/OAI/Computability/MinUncut/Games/FinalCNFPattern.lean +103 -0
  32. lean/OAI/Computability/MinUncut/Games/FinalCNFStream.lean +688 -0
  33. lean/OAI/Computability/MinUncut/Games/FiniteNoise.lean +94 -0
  34. lean/OAI/Computability/MinUncut/Games/GraphCounterModel.lean +563 -0
  35. lean/OAI/Computability/MinUncut/Games/GraphIterationBounds.lean +77 -0
  36. lean/OAI/Computability/MinUncut/Games/HintSections.lean +83 -0
  37. lean/OAI/Computability/MinUncut/Games/HintSimulation.lean +154 -0
  38. lean/OAI/Computability/MinUncut/Games/HintSoundness.lean +74 -0
  39. lean/OAI/Computability/MinUncut/Games/IncidenceProbability.lean +527 -0
  40. lean/OAI/Computability/MinUncut/Games/JointCoefficient.lean +86 -0
  41. lean/OAI/Computability/MinUncut/Games/JointHintBound.lean +141 -0
  42. lean/OAI/Computability/MinUncut/Games/JointHintSampling.lean +74 -0
  43. lean/OAI/Computability/MinUncut/Games/JointInner.lean +208 -0
  44. lean/OAI/Computability/MinUncut/Games/KernelSampling.lean +208 -0
  45. lean/OAI/Computability/MinUncut/Games/LabelBound.lean +267 -0
  46. lean/OAI/Computability/MinUncut/Games/MaskRowKernel.lean +143 -0
  47. lean/OAI/Computability/MinUncut/Games/OuterQuestions.lean +757 -0
  48. lean/OAI/Computability/MinUncut/Games/Parameters.lean +110 -0
  49. lean/OAI/Computability/MinUncut/Games/Pinsker.lean +517 -0
  50. lean/OAI/Computability/MinUncut/Games/PoweringGlobalEnumeration.lean +91 -0
lean/OAI/Computability/MinUncut/Estimates/RowListBridge.lean ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.InnerAssembly
3
+ import OAI.Computability.MinUncut.Estimates.FourthTest
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ noncomputable section
9
+ open scoped BigOperators
10
+ namespace MinUncut.Composition
11
+ open BinaryFourier hiding F₂
12
+ open MinUncut.Inner RowNoise
13
+ attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype
14
+ variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
15
+ {m n : ℕ}
16
+
17
+ attribute [local irreducible] MinUncut.Inner.gradient
18
+
19
+ lemma oddAtom_iff_labelList {R : Type*} [Fintype R] [DecidableEq R]
20
+ (r : R) (F : (R → Forms A) → ℝ) (D : Rest (W := Forms A) r)
21
+ {θ : ℝ} (hθ : 0<θ) :
22
+ θ≤oddAtom r (AffineMap.const F₂ A 1) F D ↔
23
+ (labelList (fun b => F (joinRow r b D)) θ).Nonempty := by
24
+ constructor
25
+ · intro h
26
+ have he : ∃ α : Module.Dual F₂ (Forms A),
27
+ oddAtom r (AffineMap.const F₂ A 1) F D =
28
+ if α (AffineMap.const F₂ A 1)=1 then |rowCoefficient r F α D| else 0 := by
29
+ obtain ⟨α,_,he⟩ := Finset.exists_mem_eq_sup' (s := Finset.univ) Finset.univ_nonempty
30
+ (fun α : Module.Dual F₂ (Forms A) =>
31
+ if α (AffineMap.const F₂ A 1)=1 then |rowCoefficient r F α D| else 0)
32
+ exact ⟨α,he⟩
33
+ obtain ⟨α,he⟩ := he
34
+ rw [he] at h
35
+ split_ifs at h with ho
36
+ · obtain ⟨a,rfl⟩ := oddFrequency_exists_label α ho
37
+ exact ⟨a, (mem_labelList _ θ a).mpr h⟩
38
+ · linarith
39
+ · rintro ⟨a,ha⟩
40
+ exact ((mem_labelList _ θ a).mp ha).trans
41
+ (rowCoefficient_le_oddAtom r (AffineMap.const F₂ A 1)
42
+ F (labelFrequency a) (labelFrequency_odd a) D)
43
+
44
+ lemma rowAtom_iff_list (f : FoldedProof A) (σ η : ℝ) {θ : ℝ} (hθ : 0<θ)
45
+ (x : Point m n) (i : Fin m)
46
+ (D : Rest (W := Forms A) (⟨i,face x i⟩ : Row m n)) (c : Point m n → ℝ) :
47
+ θ≤rowAtom f σ η x i D c ↔
48
+ (labelList (comparisonRow f σ η c x ⟨i,face x i⟩ D) θ).Nonempty :=
49
+ oddAtom_iff_labelList (⟨i,face x i⟩ : Row m n) (fun B => gradient f B σ η c x) D hθ
50
+
51
+ lemma rowAtomIndicator_eq_list (f : FoldedProof A) (σ η : ℝ) {θ : ℝ} (hθ : 0<θ)
52
+ (x : Point m n) (i : Fin m)
53
+ (D : Rest (W := Forms A) (⟨i,face x i⟩ : Row m n)) (c : Point m n → ℝ) :
54
+ rowAtomIndicator f σ η θ x i D c =
55
+ if (labelList (comparisonRow f σ η c x ⟨i,face x i⟩ D) θ).Nonempty then 1 else 0 := by
56
+ simp only [rowAtomIndicator,rowAtom_iff_list f σ η hθ]
57
+
58
+ end MinUncut.Composition
59
+
60
+ end
61
+ end
62
+
63
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/SamplerAssembly.lean ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.SamplerCost
3
+ import OAI.Computability.MinUncut.Search.RationalDenominatorArithmetic
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ noncomputable section
9
+ open scoped BigOperators
10
+ namespace MinUncut.Outer
11
+ open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothness
12
+ attribute [local instance] Classical.propDecidable coordsDecEq
13
+ variable {Name I S : Type*} [Fintype I] [Fintype S] [Nonempty S]
14
+
15
+ lemma allWeight_mass (equations : S → Equation Name) {k m n : ℕ} (hk : k≤Fintype.card I)
16
+ (g : GridData) (hT : 0<g.T) (hL : 0<g.L) (a : ℚ) (b : Test → ℚ) :
17
+ (∑ e : AllElementary (I := I) equations k m n g, allWeight equations g a b e)=∑ j, (b j)⁻¹ := by
18
+ apply (Rat.cast_injective (α := ℝ))
19
+ simp only [Rat.cast_sum,Rat.cast_inv,Fintype.sum_prod_type,allWeight,
20
+ elementaryWeight_mass equations hk g hT hL]
21
+
22
+ structure Parameters (J : ℕ) where
23
+ hJ : 1≤J
24
+ d : InnerData
25
+ hd : d.Check J
26
+ o : OuterData
27
+ ho : o.Check J d
28
+
29
+ namespace Parameters
30
+
31
+ def select (J : ℕ) (hJ : 1≤J) : Parameters J :=
32
+ let d := InnerData.search J hJ
33
+ let hd := InnerData.search_check J hJ
34
+ let o := OuterData.search J hJ d hd
35
+ ⟨hJ,d,hd,o,OuterData.search_check J hJ d hd⟩
36
+
37
+ def grid {J : ℕ} (P : Parameters J) : GridData :=
38
+ tableGrid P.d.m P.d.n (tableAccuracy J P.d P.o) (tableAccuracy_pos P.hJ P.d P.hd P.o P.ho)
39
+
40
+ lemma grid_pos {J : ℕ} (P : Parameters J) : 0<P.grid.T ∧ 0<P.grid.L := by
41
+ have h := tableGrid_check P.d.m P.d.n (tableAccuracy J P.d P.o)
42
+ (tableAccuracy_pos P.hJ P.d P.hd P.o P.ho)
43
+ exact ⟨h.1,h.2.1⟩
44
+
45
+ lemma t_pos {J : ℕ} (P : Parameters J) : 0<P.o.t := P.ho.2.2.2.1
46
+ lemma k_le {J : ℕ} (P : Parameters J) : P.o.k≤P.o.t := P.ho.2.2.2.2.1
47
+
48
+ def denominator {J : ℕ} (P : Parameters J) (S : Type*) [Fintype S] : ℕ :=
49
+ samplerDenominator (Fin P.o.t) S P.o.k P.d.m P.d.n P.grid
50
+ (rationalRate J P.d) (rationalBudgets J P.d P.o)
51
+
52
+ lemma denominator_pos {J : ℕ} (P : Parameters J) : 0<P.denominator S :=
53
+ samplerDenominator_pos (by simpa only [Fintype.card_fin] using P.k_le) _ _ _
54
+
55
+ abbrev Sample {J : ℕ} (P : Parameters J) (equations : S → Equation Name) :=
56
+ AllElementary (I := Fin P.o.t) equations P.o.k P.d.m P.d.n P.grid
57
+
58
+ def weight {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (e : P.Sample equations) : ℚ :=
59
+ allWeight equations P.grid (rationalRate J P.d) (rationalBudgets J P.d P.o) e
60
+
61
+ def demand {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (e : P.Sample equations) :
62
+ PathRealization.Demand (FamilyVariable Name (Fin P.o.t)) :=
63
+ allDemand equations P.grid (rationalSigma J) (rationalEta J) e
64
+
65
+ omit [Nonempty S] in
66
+ lemma weight_nonneg {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (e : P.Sample equations) :
67
+ 0≤P.weight equations e :=
68
+ elementaryWeight_nonneg equations P.grid P.grid_pos.1 P.grid_pos.2
69
+ (rationalRate_bounds P.hJ P.d P.hd).1 (rationalRate_bounds P.hJ P.d P.hd).2
70
+ (rationalBudgets_pos P.hJ P.d P.hd P.o P.ho e.1) e.1 e.2
71
+
72
+ lemma weight_den {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (e : P.Sample equations) :
73
+ (P.weight equations e).den∣P.denominator S :=
74
+ elementaryWeight_den equations (by simpa only [Fintype.card_fin] using P.k_le) _ _ _ e.1 e.2
75
+
76
+ lemma weight_sum {J : ℕ} (P : Parameters J) (equations : S → Equation Name) :
77
+ (∑ e, P.weight equations e)=rationalWeight J P.d P.o :=
78
+ allWeight_mass equations (by simpa only [Fintype.card_fin] using P.k_le) _ P.grid_pos.1 P.grid_pos.2 _ _
79
+
80
+ omit [Nonempty S] in
81
+ lemma failure_eq {J : ℕ} (P : Parameters J) (equations : S → Equation Name)
82
+ (y : FamilyVariable Name (Fin P.o.t) → Bool) :
83
+ (∑ e, (P.weight equations e:ℝ)*(PathRealization.failure (P.demand equations e) y:ℝ))=
84
+ (variableProof y).finiteCost (P.d.realize P.hJ P.hd) (P.o.realize P.hJ P.d P.hd P.ho) P.grid equations :=
85
+ allFailure_eq P.hJ P.d P.hd P.o P.ho P.grid equations y
86
+
87
+ end Parameters
88
+ end MinUncut.Outer
89
+
90
+ end
91
+ end
92
+
93
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/SamplerCost.lean ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Search.RationalInner
3
+ import OAI.Computability.MinUncut.Estimates.WeightedTestLaw
4
+
5
+ namespace OAI
6
+
7
+ noncomputable section
8
+ open scoped BigOperators
9
+ namespace MinUncut.Outer
10
+ open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothness
11
+ attribute [local instance] Classical.propDecidable coordsDecEq
12
+ variable {Name I S : Type*} [Fintype I] [Fintype S]
13
+
14
+ abbrev AllElementary (equations : S → Equation Name) (k m n : ℕ) (g : GridData) :=
15
+ Test × Elementary (I := I) equations k m n g
16
+
17
+ def allWeight (equations : S → Equation Name) {k m n : ℕ} (g : GridData) (a : ℚ) (b : Test → ℚ)
18
+ (e : AllElementary (I := I) equations k m n g) : ℚ :=
19
+ elementaryWeight equations g a (b e.1) e.1 e.2
20
+
21
+ def allDemand (equations : S → Equation Name) {k m n : ℕ} (g : GridData) (σ η : ℚ)
22
+ (e : AllElementary (I := I) equations k m n g) : PathRealization.Demand (FamilyVariable Name I) :=
23
+ (elementaryQuery equations g σ η e.1 e.2).signed familyBase
24
+
25
+ def rationalRate (J : ℕ) (d : InnerData) : ℚ := (rationalEta J)^2/d.m
26
+
27
+ lemma rationalRate_cast (J : ℕ) (d : InnerData) :
28
+ (rationalRate J d:ℝ)=(sourceEta J)^2/d.m := by
29
+ simp only [rationalRate,Rat.cast_div,Rat.cast_pow,Rat.cast_natCast,rationalEta_cast]
30
+
31
+ lemma rationalRate_bounds {J : ℕ} (hJ : 1≤J) (d : InnerData) (hd : d.Check J) :
32
+ 0≤rationalRate J d ∧ rationalRate J d≤1 := by
33
+ have ha := source_row_rate (by exact_mod_cast hJ : (1:ℝ)≤J)
34
+ (by have := (d.realize hJ hd).hm; change 2≤d.m at this; omega : 0<d.m)
35
+ rw [← rationalRate_cast] at ha
36
+ exact ⟨by exact_mod_cast ha.1,by exact_mod_cast ha.2.1⟩
37
+
38
+ lemma allFailure_eq {J : ℕ} (hJ : 1≤J) (d : InnerData) (hd : d.Check J)
39
+ (o : OuterData) (ho : o.Check J d) (g : GridData) (equations : S → Equation Name)
40
+ (y : FamilyVariable Name I → Bool) :
41
+ (∑ e : AllElementary (I := I) equations o.k d.m d.n g,
42
+ (allWeight equations g (rationalRate J d) (rationalBudgets J d o) e:ℝ)*
43
+ (PathRealization.failure (allDemand equations g (rationalSigma J) (rationalEta J) e) y:ℝ)) =
44
+ (variableProof y).finiteCost (d.realize hJ hd) (o.realize hJ d hd ho) g equations := by
45
+ rw [Fintype.sum_prod_type]
46
+ unfold ProofFamily.finiteCost
47
+ apply Finset.sum_congr rfl
48
+ intro j _
49
+ simp only [allWeight,allDemand,QueryDemand.failure_signed,← variableProof_queryAnswer]
50
+ rw [elementary_weighted_sum]
51
+ cases j <;> simp only [ProofFamily.finiteErrors,rationalBudgets_cast hJ d hd o ho,
52
+ rationalRate_cast]
53
+ all_goals
54
+ change edgeMean equations o.k (fun U h pos => _ / _) =
55
+ edgeMean equations o.k (fun U h pos => _) / _
56
+ unfold edgeMean
57
+ simp only [Finset.expect_div]
58
+ rfl
59
+ end MinUncut.Outer
60
+
61
+ namespace MinUncut.Outer
62
+ open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothness
63
+ attribute [local instance] Classical.propDecidable coordsDecEq
64
+ variable {m n : ℕ}
65
+
66
+ lemma noiseWeight_mean {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
67
+ (a : ℚ) (B : FaceArray A m n) (j : Test) : (𝔼 C, (noiseWeight a B C j:ℝ))=1 := by
68
+ cases j with
69
+ | second =>
70
+ have hh := RowNoise.rationalDensity_mean a B
71
+ have hc := congrArg (fun x : ℚ => (x:ℝ)) hh
72
+ simpa only [Fintype.expect_eq_sum_div_card,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast,
73
+ Rat.cast_one,noiseWeight] using hc
74
+ | first => simp only [noiseWeight,Rat.cast_one,Fintype.expect_const]
75
+ | third => simp only [noiseWeight,Rat.cast_one,Fintype.expect_const]
76
+ | fourth => simp only [noiseWeight,Rat.cast_one,Fintype.expect_const]
77
+
78
+ lemma gridWeight_mass (g : GridData) (hT : 0<g.T) (hL : 0<g.L) :
79
+ (∑ q : TestCoordinates m n → Fin g.L, (gridWeight g q:ℝ))=1 := by
80
+ exact_mod_cast sum_gridWeight (m := m) (n := n) g hT hL
81
+
82
+ lemma localWeight_mass {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
83
+ (g : GridData) (hT : 0<g.T) (hL : 0<g.L) (a b : ℚ) (j : Test) :
84
+ (∑ p : LocalSample A m n g, (localWeight g a b j p:ℝ))=(b:ℝ)⁻¹ := by
85
+ have hh := localWeight_sum (A := A) (m := m) (n := n) g a b j (fun _ => 1)
86
+ simp only [mul_one,← Finset.sum_mul,gridWeight_mass g hT hL,one_mul,Fintype.expect_const,
87
+ noiseWeight_mean,one_div] at hh
88
+ exact hh
89
+
90
+ variable {Name I S : Type*} [Fintype I] [Fintype S] [Nonempty S] {k : ℕ}
91
+ lemma elementaryWeight_mass (equations : S → Equation Name) (hk : k≤Fintype.card I)
92
+ (g : GridData) (hT : 0<g.T) (hL : 0<g.L) (a b : ℚ) (j : Test) :
93
+ (∑ e : Elementary (I := I) equations k m n g, (elementaryWeight equations g a b j e:ℝ))=(b:ℝ)⁻¹ := by
94
+ let : Nonempty (FixedSets I k) := fixedSets_nonempty hk
95
+ change (∑ e : Sigma _, _) = _
96
+ rw [Fintype.sum_sigma]
97
+ simp only [elementaryWeight,Rat.cast_mul,Rat.cast_inv,Rat.cast_natCast,← Finset.mul_sum,
98
+ localWeight_mass g hT hL]
99
+ simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul]
100
+ have hc : (Fintype.card (OuterSample I S k):ℝ)≠0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero
101
+ field_simp
102
+ end MinUncut.Outer
103
+
104
+ end
105
+
106
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/SecondFailureIndicator.lean ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Analysis.SmoothingRho
3
+ import OAI.Computability.MinUncut.Games.JointInner
4
+ import OAI.Computability.MinUncut.Analysis.RowProjectedGradient
5
+
6
+ namespace OAI
7
+
8
+ noncomputable section
9
+ open scoped BigOperators
10
+ open MeasureTheory ProbabilityTheory Filter
11
+ open scoped Topology NNReal
12
+ open scoped BigOperators
13
+ open MeasureTheory ProbabilityTheory Polynomial Filter
14
+ open scoped BigOperators Topology
15
+ open MeasureTheory ProbabilityTheory WithLp
16
+ open scoped BigOperators RealInnerProductSpace
17
+ open scoped BigOperators
18
+ namespace MinUncut.Inner
19
+ open MeasureTheory ProbabilityTheory
20
+ open scoped BigOperators
21
+ attribute [local instance] Classical.propDecidable
22
+ attribute [local irreducible] query pullQuery
23
+ variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
24
+ variable {m n : ℕ}
25
+
26
+ omit [Fintype A] in
27
+ lemma secondFailure_indicator (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ)
28
+ (c : Point m n → ℝ) (p : (Point m n → ℝ) × (Code m n → ℝ)) :
29
+ secondFailure f B C σ η c p =
30
+ (coupledAnswer f B σ η c p-coupledAnswer f C σ η c p)^2/4 := by
31
+ have h := secondFailure_eq f B C σ η c p
32
+ linarith
33
+
34
+ lemma secondRejection_measurable (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) :
35
+ Measurable (secondRejection f B C σ η) := by
36
+ have hh (B : FaceArray A m n) : Measurable
37
+ (fun u : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) =>
38
+ coupledAnswer f B σ η u.1 u.2) := by
39
+ have hm : Measurable (fun u : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) =>
40
+ (u.1+σ•u.2.1,u.2.2)) := by fun_prop
41
+ exact (measurable_answer f B η).comp hm
42
+ have hm : Measurable (fun u : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) =>
43
+ secondFailure f B C σ η u.1 u.2) := by
44
+ simp_rw [secondFailure_indicator]
45
+ exact ((hh B).sub (hh C)).pow_const 2 |>.div_const 4
46
+ exact hm.stronglyMeasurable.integral_prod_right.measurable
47
+
48
+ lemma secondRejection_range (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ)
49
+ (c : Point m n → ℝ) : 0≤ secondRejection f B C σ η c ∧ secondRejection f B C σ η c≤1 := by
50
+ have hm : Measurable (secondFailure f B C σ η c) := by
51
+ change Measurable (fun p => secondFailure f B C σ η c p)
52
+ simp_rw [secondFailure_indicator]
53
+ exact ((coupledAnswer_measurable f B σ η c).sub
54
+ (coupledAnswer_measurable f C σ η c)).pow_const 2 |>.div_const 4
55
+ have hb (p : (Point m n → ℝ) × (Code m n → ℝ)) :
56
+ 0≤ secondFailure f B C σ η c p ∧ secondFailure f B C σ η c p≤1 := by
57
+ unfold secondFailure; split_ifs <;> norm_num
58
+ have hi : Integrable (secondFailure f B C σ η c)
59
+ ((gauss (Point m n)).prod (gauss (Code m n))) :=
60
+ Integrable.of_bound hm.aestronglyMeasurable 1 (ae_of_all _ (fun p => by
61
+ rw [Real.norm_eq_abs,abs_of_nonneg (hb p).1]; exact (hb p).2))
62
+ constructor
63
+ · exact integral_nonneg (fun p => (hb p).1)
64
+ · unfold secondRejection
65
+ simpa only [integral_const,MeasureTheory.probReal_univ,one_smul] using
66
+ integral_mono hi (integrable_const 1) (fun p => (hb p).2)
67
+
68
+ lemma secondRejection_integrable (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) :
69
+ Integrable (secondRejection f B C σ η) (gauss (Point m n)) :=
70
+ Integrable.of_bound (secondRejection_measurable f B C σ η).aestronglyMeasurable 1
71
+ (ae_of_all _ (fun c => by
72
+ rw [Real.norm_eq_abs,abs_of_nonneg (secondRejection_range f B C σ η c).1]
73
+ exact (secondRejection_range f B C σ η c).2))
74
+
75
+ lemma rowProjectedGradient_memLp (D : ℕ) (f : FoldedProof A) (B : FaceArray A m n)
76
+ {σ : ℝ} (hσ : σ≠0) (η : ℝ) (x : Point m n) :
77
+ MemLp (fun c => rowProjectedGradient D f σ η B c x) 2 (gauss (Point m n)) := by
78
+ unfold rowProjectedGradient RowNoise.project
79
+ apply memLp_finsetSum
80
+ intro α _
81
+ apply MemLp.mul_const
82
+ unfold BinaryFourier.coefficient
83
+ simp only [Fintype.expect_eq_sum_div_card, div_eq_mul_inv]
84
+ exact (memLp_finsetSum _ (fun C _ => (gradient_memLp f C hσ η x).mul_const _)).mul_const _
85
+
86
+ lemma rowResidualEnergy_integrable (D : ℕ) (f : FoldedProof A) (B : FaceArray A m n)
87
+ {σ : ℝ} (hσ : σ≠0) (η : ℝ) :
88
+ Integrable (fun c => spatialEnergy (fun x => gradient f B σ η c x-
89
+ rowProjectedGradient D f σ η B c x)) (gauss (Point m n)) := by
90
+ unfold spatialEnergy
91
+ exact (integrable_finsetSum _ (fun x _ =>
92
+ ((gradient_memLp f B hσ η x).sub (rowProjectedGradient_memLp D f B hσ η x)).integrable_sq)).const_mul _
93
+
94
+ theorem gradient_row_tail_average (f : FoldedProof A) (hn : 0 < n)
95
+ {σ a : ℝ} (hσ : σ≠0) (ha : 0≤a) (ha1 : a≤1) (η : ℝ) (D : ℕ)
96
+ (hD : ∀ k : ℕ, D < k → 1≤(k:ℝ)*a) :
97
+ (𝔼 B : FaceArray A m n, ∫ c, spatialEnergy (fun x =>
98
+ gradient f B σ η c x-rowProjectedGradient D f σ η B c x) ∂gauss (Point m n)) ≤
99
+ 4*σ⁻¹^2*(𝔼 B : FaceArray A m n, 𝔼 C : FaceArray A m n,
100
+ RowNoise.density a B C*(∫ c, secondRejection f B C σ η c ∂gauss (Point m n))) := by
101
+ have hl : Integrable (fun c => 𝔼 B : FaceArray A m n, spatialEnergy (fun x =>
102
+ gradient f B σ η c x-rowProjectedGradient D f σ η B c x)) (gauss (Point m n)) := by
103
+ simp only [Fintype.expect_eq_sum_div_card]
104
+ exact (integrable_finsetSum _ (fun B _ => rowResidualEnergy_integrable D f B hσ η)).div_const _
105
+ have hr : Integrable (fun c => 4*σ⁻¹^2*(𝔼 B : FaceArray A m n, 𝔼 C : FaceArray A m n,
106
+ RowNoise.density a B C*secondRejection f B C σ η c)) (gauss (Point m n)) := by
107
+ simp only [Fintype.expect_eq_sum_div_card]
108
+ apply Integrable.const_mul
109
+ apply Integrable.div_const
110
+ apply integrable_finsetSum
111
+ intro B _
112
+ exact (integrable_finsetSum _ (fun C _ =>
113
+ (secondRejection_integrable f B C σ η).const_mul _)).div_const _
114
+ have h := integral_mono hl hr (fun c => gradient_row_tail f hn hσ ha ha1 η D hD c)
115
+ simpa only [Fintype.expect_eq_sum_div_card,integral_div,integral_const_mul,
116
+ integral_finsetSum _ (fun B _ => rowResidualEnergy_integrable D f B hσ η),
117
+ integral_finsetSum _ (fun B _ =>
118
+ (integrable_finsetSum _ (fun C _ => (secondRejection_integrable f B C σ η).const_mul _)).div_const _),
119
+ integral_finsetSum _ (fun C _ => (secondRejection_integrable f _ C σ η).const_mul _)] using h
120
+ end MinUncut.Inner
121
+ namespace MinUncut.RowNoise
122
+ open MeasureTheory ProbabilityTheory BinaryFourier GaussianHermite
123
+ open scoped BigOperators
124
+ attribute [local instance] Classical.propDecidable
125
+ local instance secondFailureDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] :
126
+ Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintype
127
+ variable {R W ι : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W]
128
+ [AddCommGroup W] [Module F₂ W] [Fintype ι] [DecidableEq ι]
129
+
130
+ lemma project_eq_mask_sum (D : ℕ) (f : (R → W) → ℝ) (B : R → W) :
131
+ project D f B = ∑ S ∈ Finset.univ.filter (fun S : Finset R => S.card ≤ D), maskProject S f B := by
132
+ simp only [maskProject_expansion]
133
+ rw [Finset.sum_comm]
134
+ simp only [Finset.sum_filter]
135
+ unfold project
136
+ rw [Finset.sum_filter]
137
+ apply Finset.sum_congr rfl
138
+ intro α _
139
+ rw [Finset.sum_eq_single (mask α)]
140
+ · simp [degree]
141
+ rfl
142
+ · intro S _ hS
143
+ simp [Ne.symm hS]
144
+ · simp
145
+
146
+ omit [DecidableEq W] in
147
+ lemma project_sum {T : Type*} (s : Finset T) (D : ℕ) (u : T → (R → W) → ℝ) (B : R → W) :
148
+ project D (fun C => ∑ t ∈ s, u t C) B = ∑ t ∈ s, project D (u t) B := by
149
+ unfold project BinaryFourier.coefficient
150
+ simp only [Finset.sum_mul,Finset.expect_sum_comm]
151
+ rw [Finset.sum_comm]
152
+
153
+ omit [DecidableEq W] in
154
+ lemma project_sub (D : ℕ) (f g : (R → W) → ℝ) (B : R → W) :
155
+ project D (fun C => f C-g C) B = project D f B-project D g B := by
156
+ simp only [project,BinaryFourier.coefficient,sub_mul,Finset.expect_sub_distrib,Finset.sum_sub_distrib]
157
+
158
+ omit [DecidableEq W] in
159
+ lemma project_energy_le (D : ℕ) (f : (R → W) → ℝ) :
160
+ (𝔼 B, (project D f B)^2) ≤ 𝔼 B, (f B)^2 := by
161
+ rw [← BinaryFourier.parseval,← BinaryFourier.parseval]
162
+ simp only [coefficient_project]
163
+ apply Finset.sum_le_sum
164
+ intro α _
165
+ split_ifs <;> simp [sq_nonneg]
166
+
167
+ omit [DecidableEq ι] in
168
+ lemma project_memLp (D : ℕ) (u : (R → W) → (ι → ℝ) → ℝ)
169
+ (hu : ∀ B, MemLp (u B) 2 (γpi ι)) (B : R → W) :
170
+ MemLp (fun c => project D (fun C => u C c) B) 2 (γpi ι) := by
171
+ simp_rw [project_eq_mask_sum]
172
+ exact memLp_finsetSum _ (fun S _ => memLp_maskProject S u hu B)
173
+
174
+ def rectangle (D s : ℕ) : Finset (Finset R × (ι → ℕ)) :=
175
+ (Finset.univ.filter (fun S : Finset R => S.card≤D)).product (GaussianHermite.low s)
176
+
177
+ lemma rectangle_eq_composition (D s : ℕ) (u : (R → W) → (ι → ℝ) → ℝ)
178
+ (B : R → W) (c : ι → ℝ) :
179
+ selectedProject (rectangle D s) u B c =
180
+ project D (fun C => GaussianHermite.project s (u C) c) B := by
181
+ unfold selectedProject rectangle
182
+ have he := Finset.sum_product
183
+ (Finset.univ.filter (fun S : Finset R => S.card≤D)) (GaussianHermite.low s)
184
+ (fun j => maskHermite j.1 j.2 u B c)
185
+ change (∑ j ∈ (Finset.univ.filter (fun S : Finset R => S.card≤D)) ×ˢ
186
+ (GaussianHermite.low s), maskHermite j.1 j.2 u B c) = _
187
+ rw [he]
188
+ simp only [GaussianHermite.project]
189
+ rw [project_sum]
190
+ simp only [project_eq_mask_sum]
191
+ rw [Finset.sum_comm]
192
+ apply Finset.sum_congr rfl
193
+ intro I _
194
+ apply Finset.sum_congr rfl
195
+ intro S _
196
+ simp only [maskHermite,hermiteComponent,mul_comm]
197
+
198
+ omit [DecidableEq ι] in
199
+ lemma jointEnergy_project_le (D : ℕ) (u : (R → W) → (ι → ℝ) → ℝ)
200
+ (hu : ∀ B, MemLp (u B) 2 (γpi ι)) :
201
+ jointEnergy (fun B c => project D (fun C => u C c) B) ≤ jointEnergy u := by
202
+ unfold jointEnergy
203
+ rw [← integral_expect _ (fun B => (project_memLp D u hu B).integrable_sq),
204
+ ← integral_expect _ (fun B => (hu B).integrable_sq)]
205
+ apply integral_mono
206
+ · simp only [Fintype.expect_eq_sum_div_card]
207
+ exact (integrable_finsetSum _ (fun B _ => (project_memLp D u hu B).integrable_sq)).div_const _
208
+ · simp only [Fintype.expect_eq_sum_div_card]
209
+ exact (integrable_finsetSum _ (fun B _ => (hu B).integrable_sq)).div_const _
210
+ · intro c; exact project_energy_le D (fun B => u B c)
211
+
212
+ omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] [DecidableEq ι] in
213
+ lemma jointEnergy_add_le (u v : (R → W) → (ι → ℝ) → ℝ)
214
+ (hu : ∀ B, MemLp (u B) 2 (γpi ι)) (hv : ∀ B, MemLp (v B) 2 (γpi ι)) :
215
+ jointEnergy (fun B c => u B c+v B c) ≤ 2*jointEnergy u+2*jointEnergy v := by
216
+ have hB (B : R → W) : (∫ c, (u B c+v B c)^2 ∂γpi ι) ≤
217
+ 2*(∫ c, (u B c)^2 ∂γpi ι)+2*(∫ c, (v B c)^2 ∂γpi ι) := by
218
+ calc
219
+ _ ≤ ∫ c, 2*(u B c)^2+2*(v B c)^2 ∂γpi ι :=
220
+ integral_mono ((hu B).add (hv B)).integrable_sq
221
+ (((hu B).integrable_sq.const_mul 2).add ((hv B).integrable_sq.const_mul 2))
222
+ (fun c => by
223
+ change (u B c+v B c)^2 ≤ 2*(u B c)^2+2*(v B c)^2
224
+ nlinarith [sq_nonneg (u B c-v B c)])
225
+ _ = _ := by rw [integral_add ((hu B).integrable_sq.const_mul 2) ((hv B).integrable_sq.const_mul 2),integral_const_mul,integral_const_mul]
226
+ simpa only [jointEnergy,Finset.expect_add_distrib,← Finset.mul_expect] using
227
+ Finset.expect_le_expect (s := Finset.univ) (fun B _ => hB B)
228
+
229
+ theorem rectangle_residual_le (D s : ℕ) (u : (R → W) → (ι → ℝ) → ℝ)
230
+ (hu : ∀ B, MemLp (u B) 2 (γpi ι)) :
231
+ jointEnergy (fun B c => u B c-selectedProject (rectangle D s) u B c) ≤
232
+ 2*jointEnergy (fun B c => u B c-project D (fun C => u C c) B)+
233
+ 2*jointEnergy (fun B c => u B c-GaussianHermite.project s (u B) c) := by
234
+ let v := fun B c => u B c-project D (fun C => u C c) B
235
+ let w := fun B c => u B c-GaussianHermite.project s (u B) c
236
+ have hv (B) : MemLp (v B) 2 (γpi ι) := (hu B).sub (project_memLp D u hu B)
237
+ have hw (B) : MemLp (w B) 2 (γpi ι) := (hu B).sub (GaussianHermite.memLp_project s (u B))
238
+ have he (B c) : u B c-selectedProject (rectangle D s) u B c =
239
+ v B c+project D (fun C => w C c) B := by
240
+ rw [rectangle_eq_composition]
241
+ simp only [v,w,project_sub]
242
+ ring
243
+ simp_rw [he]
244
+ exact (jointEnergy_add_le v (fun B c => project D (fun C => w C c) B) hv
245
+ (project_memLp D w hw)).trans (add_le_add_right
246
+ (mul_le_mul_of_nonneg_left (jointEnergy_project_le D w hw) (show (0 : ℝ) ≤ 2 by norm_num)) _)
247
+
248
+ lemma rectangle_energy_identity (D s : ℕ) (u : (R → W) → (ι → ℝ) → ℝ)
249
+ (hu : ∀ B, MemLp (u B) 2 (γpi ι)) :
250
+ jointEnergy (selectedProject (rectangle D s) u) = jointEnergy u-
251
+ jointEnergy (fun B c => u B c-selectedProject (rectangle D s) u B c) := by
252
+ rw [jointEnergy_sub u _ hu (memLp_selectedProject _ _),
253
+ selectedProject_source_inner _ u hu,← selectedProject_energy]
254
+ ring
255
+ end MinUncut.RowNoise
256
+
257
+ end
258
+
259
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/SelectedProject.lean ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Analysis.MaskHermite
3
+
4
+ namespace OAI
5
+
6
+ noncomputable section
7
+ open scoped BigOperators
8
+ open MeasureTheory ProbabilityTheory Filter
9
+ open scoped Topology NNReal
10
+ open scoped BigOperators
11
+ open MeasureTheory ProbabilityTheory Polynomial Filter
12
+ open scoped BigOperators Topology
13
+ open MeasureTheory ProbabilityTheory WithLp
14
+ open scoped BigOperators RealInnerProductSpace
15
+ namespace MinUncut.RowNoise
16
+ open MeasureTheory ProbabilityTheory BinaryFourier GaussianHermite
17
+ open scoped BigOperators
18
+ local instance selectedProjectDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] :
19
+ Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintype
20
+ variable {R W ι : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W]
21
+ [AddCommGroup W] [Module F₂ W] [Fintype ι]
22
+
23
+ def selectedProject (J : Finset (Finset R × (ι → ℕ)))
24
+ (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) (c : ι → ℝ) : ℝ :=
25
+ ∑ j ∈ J, maskHermite j.1 j.2 u B c
26
+
27
+ omit [AddCommGroup W] [Module F₂ W] in
28
+ lemma memLp_selectedProject (J : Finset (Finset R × (ι → ℕ)))
29
+ (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) :
30
+ MemLp (selectedProject J u B) 2 (γpi ι) :=
31
+ memLp_finsetSum _ (fun j _ => memLp_maskHermite j.1 j.2 u B)
32
+
33
+ lemma selectedProject_atom_mean (J : Finset (Finset R × (ι → ℕ))) (r : R) (one : W)
34
+ (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) :
35
+ (𝔼 D, ∫ c, oddAtom r one (fun B => selectedProject J u B c) D ∂γpi ι) ≤
36
+ J.card * (2:ℝ)^Fintype.card R * Real.sqrt
37
+ (𝔼 D, ∫ c, (oddAtom r one (fun B => u B c) D)^2 ∂γpi ι) := by
38
+ have hi (D : Rest (W := W) r) := (memLp_oddAtom r one (selectedProject J u)
39
+ (memLp_selectedProject J u) D).integrable (by norm_num)
40
+ have hj (j : Finset R × (ι → ℕ)) (D : Rest (W := W) r) :=
41
+ (memLp_oddAtom r one (maskHermite j.1 j.2 u) (memLp_maskHermite j.1 j.2 u) D).integrable (by norm_num)
42
+ calc
43
+ _ ≤ 𝔼 D, ∫ c, (∑ j ∈ J, oddAtom r one (fun B => maskHermite j.1 j.2 u B c) D) ∂γpi ι := by
44
+ apply Finset.expect_le_expect
45
+ intro D _
46
+ exact integral_mono (hi D) (integrable_finsetSum _ (fun j _ => hj j D))
47
+ (fun c => oddAtom_sum J r one (fun j B => maskHermite j.1 j.2 u B c) D)
48
+ _ = ∑ j ∈ J, 𝔼 D, ∫ c, oddAtom r one (fun B => maskHermite j.1 j.2 u B c) D ∂γpi ι := by
49
+ simp_rw [integral_finsetSum _ (fun j _ => hj j _), Finset.expect_sum_comm]
50
+ _ ≤ ∑ _j ∈ J, (2:ℝ)^Fintype.card R * Real.sqrt
51
+ (𝔼 D, ∫ c, (oddAtom r one (fun B => u B c) D)^2 ∂γpi ι) :=
52
+ Finset.sum_le_sum (fun j _ => oddAtom_maskHermite_mean r one j.1 j.2 u hu)
53
+ _ = _ := by simp only [Finset.sum_const, nsmul_eq_mul]; ring
54
+ end MinUncut.RowNoise
55
+ open scoped BigOperators
56
+
57
+ end
58
+
59
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/SelectedProjectSliceContinuous.lean ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.FaceUpdateSelf
3
+ import OAI.Computability.MinUncut.Games.JointInner
4
+
5
+ namespace OAI
6
+
7
+ noncomputable section
8
+ open scoped BigOperators
9
+ open MeasureTheory ProbabilityTheory Filter
10
+ open scoped Topology NNReal
11
+ open scoped BigOperators
12
+ open MeasureTheory ProbabilityTheory Polynomial Filter
13
+ open scoped BigOperators Topology
14
+ open MeasureTheory ProbabilityTheory WithLp
15
+ open scoped BigOperators RealInnerProductSpace
16
+ open scoped BigOperators
17
+ namespace MinUncut.RowNoise
18
+ open MeasureTheory GaussianHermite
19
+ open scoped BigOperators
20
+ variable {R W ι : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W]
21
+ [AddCommGroup W] [Module BinaryFourier.F₂ W] [Fintype ι] [DecidableEq ι]
22
+ omit [AddCommGroup W] [Module BinaryFourier.F₂ W] in
23
+ lemma selectedProject_slice_continuous (J : Finset (Finset R × (ι → ℕ)))
24
+ (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) (C : ι → ℝ) (x : ι) :
25
+ Continuous (fun t => selectedProject J u B (Function.update C x t)) := by
26
+ have hu : Continuous (fun t => Function.update C x t) := by
27
+ apply continuous_pi
28
+ intro y
29
+ by_cases hy : y=x
30
+ · subst y
31
+ simp only [Function.update_self]
32
+ exact continuous_id
33
+ · simp only [Function.update_of_ne hy]
34
+ exact continuous_const
35
+ unfold selectedProject
36
+ apply continuous_finsetSum
37
+ intro j _
38
+ simp only [maskHermite_eq]
39
+ exact ((continuous_psi j.2).comp hu).mul_const _
40
+ end MinUncut.RowNoise
41
+
42
+ namespace MinUncut.Slice
43
+ open MeasureTheory
44
+ variable {Ω : Type*} [MeasurableSpace Ω] [TopologicalSpace Ω]
45
+ lemma centeredClip_continuous (μ : Measure Ω) (A : ℝ) (f : Ω → ℝ) (hf : Continuous f) :
46
+ Continuous (centeredClip μ A f) := by
47
+ unfold centeredClip clip
48
+ exact (continuous_const.max (hf.min continuous_const)).sub continuous_const
49
+ end MinUncut.Slice
50
+
51
+ end
52
+
53
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/SelectedSyntax.lean ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Graphs.CompleteGraphProgram
3
+ import OAI.Computability.MinUncut.Graphs.Graph
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ noncomputable section
9
+ namespace MinUncut.Preprocess
10
+ attribute [local irreducible] selectedInner selectedOuter
11
+ open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate
12
+ open MinUncutGames.Foundations MinUncutGames.Foundations.Hastad
13
+ open MinUncutGames.Integration.SourceParameters MinUncut.Costed.SourceWords MinUncut.SourceTemplate
14
+ def chosenError (K : ℕ) := (selectedParameters K).sourceError
15
+ def chosenNoise (K : ℕ) := SourceNoiseParameter.noiseDenominator (chosenError K)
16
+ def chosenRepetition (K : ℕ) :=
17
+ SourceGap.repetitionCount PCP.PCPIteration.finalClauseGap (chosenError K)
18
+ PCP.PCPIteration.finalClauseGap_positive PCP.TableGapReduction.finalClauseGap_le_one
19
+ (selectedParameters K).sourceError_pos (chosenNoise K) (SourceNoiseParameter.noiseDenominator_pos _)
20
+ lemma c_chosenError : Computable chosenError := by
21
+ have hd := ca_ratDiv (c_outerData_b4.comp c_selectedOuter) (ca_ratCast c_chosenT)
22
+ have hp:=ca_ratLe (ca_const (1/2:ℚ)) hd
23
+ exact (Computable.cond hp.decide (ca_const (1/2:ℚ)) hd).of_eq (by intro K; simp [chosenError,Outer.Parameters.sourceError,min_def,selectedParameters,chosenT])
24
+ lemma c_chosenNoise : Computable chosenNoise := by
25
+ exact ca_add (primrec_ratDen.to_comp.comp c_chosenError) (ca_const 2)
26
+ lemma c_chosenRepetition : Computable chosenRepetition := by
27
+ apply Computable.find
28
+ exact ca_and (ca_natLt (ca_const 0) Computable.snd)
29
+ (ca_ratLt (ca_ratPow (ca_const (rate (PCP.PCPIteration.finalClauseGap/3))) Computable.snd)
30
+ (ca_ratMul (ca_ratMul (ca_const 4) (ca_ratInv (ca_ratCast (c_chosenNoise.comp Computable.fst))))
31
+ (ca_ratPow (c_chosenError.comp Computable.fst) (ca_const 2))))
32
+ attribute [local irreducible] chosenRepetition chosenNoise sourceStageProgram
33
+ lemma c_selectedGraphCode : Computable (fun K=>
34
+ (completeGraphProgram (selectedParameters K) (chosenEnumeration K) (chosenRepetition K) (chosenNoise K)).code) := by
35
+ have hd := Syntax.c_demandStageCode _ c_chosenExpressions chosenT
36
+ (fun K=>(selectedParameters K).denominatorCoefficient) c_chosenT c_chosenDenominator
37
+ have hs := Syntax.c_sourceStageCode.comp (c_chosenRepetition.pair c_chosenNoise)
38
+ have hc : Computable (fun K => Turing.ToPartrec.Code.comp
39
+ (Turing.ToPartrec.Code.comp MinUncut.Costed.GraphRegisters.rawRenderer.code
40
+ (demandStageProgram
41
+ (localExpressions (chosenEnumeration K)
42
+ (rationalRate (parameterJ K) (selectedInner K))
43
+ (rationalBudgets (parameterJ K) (selectedInner K) (selectedOuter K))
44
+ (rationalSigma (parameterJ K)) (rationalEta (parameterJ K)))
45
+ (chosenT K) (selectedParameters K).denominatorCoefficient).code)
46
+ (sourceStageProgram (chosenRepetition K) (chosenNoise K)).code) :=
47
+ MinUncut.CodeEffective.computable_comp.comp
48
+ (MinUncut.CodeEffective.computable_comp.comp (ca_const MinUncut.Costed.GraphRegisters.rawRenderer.code) hd) hs
49
+ apply hc.of_eq
50
+ intro K
51
+ rfl
52
+ end MinUncut.Preprocess
53
+
54
+ end
55
+ end
56
+
57
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/SingleRow.lean ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.JointCoefficient
3
+ import OAI.Computability.MinUncut.Analysis.Hermite
4
+
5
+ namespace OAI
6
+
7
+ noncomputable section
8
+ open scoped BigOperators
9
+ open MeasureTheory ProbabilityTheory Filter
10
+ open scoped Topology NNReal
11
+ open scoped BigOperators
12
+ open MeasureTheory ProbabilityTheory Polynomial Filter
13
+ open scoped BigOperators Topology
14
+ open MeasureTheory ProbabilityTheory WithLp
15
+ open scoped BigOperators RealInnerProductSpace
16
+ namespace MinUncut.Inner
17
+ open scoped BigOperators
18
+ attribute [local instance] Classical.propDecidable
19
+ variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
20
+ variable {m n : ℕ}
21
+
22
+ def singleRow (r : Row m n) : Row m n → F₂ := Pi.single r 1
23
+
24
+ lemma rowCode_singleRow (r : Row m n) (u : Point m n) :
25
+ (rowCode (singleRow r)).val u = if face u r.1=r.2 then 1 else 0 := by
26
+ change (∑ i : Fin m, (Pi.single r (1:F₂) : Row m n → F₂) ⟨i,face u i⟩) = _
27
+ rw [Finset.sum_eq_single r.1]
28
+ · by_cases hh : face u r.1=r.2
29
+ · simp [hh]
30
+ · have he : (⟨r.1,face u r.1⟩ : Row m n) ≠ r := by
31
+ intro he; cases r; simp_all
32
+ simp [hh, Pi.single_eq_of_ne he]
33
+ · intro i _ hi
34
+ apply Pi.single_eq_of_ne
35
+ intro he
36
+ exact hi (congrArg Sigma.fst he)
37
+ · simp
38
+
39
+ omit [Fintype A] in
40
+ lemma constantArray_singleRow (r : Row m n) :
41
+ constantArray (singleRow r) = Pi.single r (AffineMap.const F₂ A 1) := by
42
+ funext t
43
+ by_cases ht : t=r
44
+ · subst t; simp [constantArray, singleRow]
45
+ · simp only [constantArray, singleRow, Pi.single_eq_of_ne ht]
46
+ rfl
47
+
48
+ theorem joint_local_odd (f : FoldedProof A) {σ : ℝ} (hσ : σ ≠ 0) (η : ℝ)
49
+ (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ)
50
+ (hne : jointCoefficient f σ η x α I ≠ 0) (i : Fin m)
51
+ (hi : ∀ u, 0 < I u → face u i ≠ face x i) :
52
+ RowNoise.frequency α ⟨i,face x i⟩ (AffineMap.const F₂ A 1) = 1 := by
53
+ have hh := joint_row_gauge f hσ η x α I hne (singleRow ⟨i,face x i⟩)
54
+ rw [constantArray_singleRow, rowCode_singleRow, ite_eq_left rfl] at hh
55
+ have hp : GaussianHermite.parity (rowCode (singleRow ⟨i,face x i⟩)).val I = 0 := by
56
+ unfold GaussianHermite.parity
57
+ apply Finset.sum_eq_zero
58
+ intro u _
59
+ by_cases hu : I u=0
60
+ · simp [hu]
61
+ · rw [rowCode_singleRow, ite_eq_right (hi u (Nat.pos_of_ne_zero hu)), zero_mul]
62
+ rw [hp, add_zero] at hh
63
+ exact hh
64
+
65
+ lemma frequency_cylinder (α : Module.Dual F₂ (FaceArray A m n))
66
+ (x : Point m n) (i j : Fin m) (hij : i ≠ j)
67
+ (hi : ∀ y, RowNoise.frequency α ⟨i,y⟩ ≠ 0 →
68
+ doubleMatch i j x (rowFill x ⟨i,y⟩) → y=face x i)
69
+ (hj : ∀ y, RowNoise.frequency α ⟨j,y⟩ ≠ 0 →
70
+ doubleMatch j i x (rowFill x ⟨j,y⟩) → y=face x j) (a : Forms A) :
71
+ α (cylinderArray i j x a) =
72
+ RowNoise.frequency α ⟨i,face x i⟩ a + RowNoise.frequency α ⟨j,face x j⟩ a := by
73
+ rw [RowNoise.dual_apply]
74
+ have he (r : Row m n) : RowNoise.frequency α r (cylinderArray i j x a r) =
75
+ (if r=⟨i,face x i⟩ then RowNoise.frequency α ⟨i,face x i⟩ a else 0) +
76
+ (if r=⟨j,face x j⟩ then RowNoise.frequency α ⟨j,face x j⟩ a else 0) := by
77
+ by_cases hr : r=⟨i,face x i⟩
78
+ · subst r
79
+ have hne : (⟨i,face x i⟩ : Row m n) ≠ ⟨j,face x j⟩ := by
80
+ intro he; exact hij (congrArg Sigma.fst he)
81
+ simp [hne, cylinderArray_local, doubleMatch]
82
+ by_cases hr' : r=⟨j,face x j⟩
83
+ · subst r
84
+ simp [hr, cylinderArray_local, doubleMatch]
85
+ simp only [ite_eq_right hr, ite_eq_right hr', zero_add]
86
+ by_cases ha : RowNoise.frequency α r=0
87
+ · simp [ha]
88
+ · unfold cylinderArray
89
+ split_ifs with hc
90
+ · rcases r with ⟨t,y⟩
91
+ rcases hc.1 with ht | ht
92
+ · change t=i at ht
93
+ subst t
94
+ exact False.elim (hr (by rw [hi y ha hc.2]))
95
+ · change t=j at ht
96
+ subst t
97
+ have hc' : doubleMatch j i x (rowFill x ⟨j,y⟩) :=
98
+ fun u huj hui => hc.2 u hui huj
99
+ exact False.elim (hr' (by rw [hj y ha hc']))
100
+ · simp
101
+ simp_rw [he]
102
+ rw [Finset.sum_add_distrib]
103
+ simp
104
+
105
+ theorem joint_matching_odd (f : FoldedProof A) {σ : ℝ} (hσ : σ ≠ 0) (η : ℝ)
106
+ (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ)
107
+ (hne : jointCoefficient f σ η x α I ≠ 0) (hx : I x=0)
108
+ (hsize : (RowNoise.mask α).card < (m-(∑ u, I u)).choose 2) :
109
+ ∃ i j : Fin m, i ≠ j ∧
110
+ RowNoise.frequency α ⟨i,face x i⟩ = RowNoise.frequency α ⟨j,face x j⟩ ∧
111
+ RowNoise.frequency α ⟨i,face x i⟩ (AffineMap.const F₂ A 1) = 1 := by
112
+ obtain ⟨i,j,hij,hs,hi,hj⟩ := admissible_pair x I (RowNoise.mask α) hx hsize
113
+ refine ⟨i,j,hij,?_,joint_local_odd f hσ η x α I hne i (fun u hu => (hs u hu).1)⟩
114
+ apply LinearMap.ext
115
+ intro a
116
+ have hh := joint_cylinder_gauge f σ η x α I hne i j hij x a
117
+ rw [frequency_cylinder α x i j hij
118
+ (fun y hy => hi y (by simpa [RowNoise.mask] using hy))
119
+ (fun y hy => hj y (by simpa [RowNoise.mask] using hy))] at hh
120
+ exact (BinaryFourier.add_eq_zero_iff _ _).mp hh
121
+ end MinUncut.Inner
122
+
123
+ end
124
+
125
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/TM2Costed.lean ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.CodeComputability
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ namespace MinUncut.Costed
8
+
9
+ open Function
10
+
11
+ def Steps {α : Type*} (f : α → Option α) (n : ℕ) (a b : α) : Prop :=
12
+ (fun x : Option α => x.bind f)^[n] (some a) = some b
13
+
14
+ @[simp] theorem steps_zero {α : Type*} (f : α → Option α) (a b : α) :
15
+ Steps f 0 a b ↔ a = b := by
16
+ simp [Steps]
17
+
18
+ theorem steps_one {α : Type*} {f : α → Option α} {a b : α}
19
+ (h : f a = some b) : Steps f 1 a b := h
20
+
21
+ theorem steps_head {α : Type*} {f : α → Option α} {n : ℕ} {a b c : α}
22
+ (h : f a = some b) (h' : Steps f n b c) : Steps f (n + 1) a c := by
23
+ simpa only [Steps, Function.iterate_succ_apply, Option.bind_some, h] using h'
24
+
25
+ theorem steps_trans {α : Type*} {f : α → Option α} {m n : ℕ} {a b c : α}
26
+ (h : Steps f m a b) (h' : Steps f n b c) : Steps f (m + n) a c := by
27
+ dsimp [Steps] at *
28
+ rw [Nat.add_comm m n, Function.iterate_add_apply, h, h']
29
+
30
+ def steps_timed {α : Type*} {f : α → Option α} {n m : ℕ} {a b : α}
31
+ (h : Steps f n a b) (hn : n ≤ m) : StateTransition.EvalsToInTime f a (some b) m :=
32
+ ⟨⟨n, h⟩, hn⟩
33
+
34
+ def Within {α : Type*} (f : α → Option α) (n : ℕ) (a b : α) : Prop :=
35
+ ∃ t, t ≤ n ∧ Steps f t a b
36
+
37
+ theorem Steps.within {α : Type*} {f : α → Option α} {n : ℕ} {a b : α}
38
+ (h : Steps f n a b) : Within f n a b := ⟨n, le_rfl, h⟩
39
+
40
+ theorem Within.mono {α : Type*} {f : α → Option α} {m n : ℕ} {a b : α}
41
+ (h : Within f m a b) (hmn : m ≤ n) : Within f n a b := by
42
+ obtain ⟨t, ht, he⟩ := h
43
+ exact ⟨t, ht.trans hmn, he⟩
44
+
45
+ theorem Within.trans {α : Type*} {f : α → Option α} {m n : ℕ} {a b c : α}
46
+ (h : Within f m a b) (h' : Within f n b c) : Within f (m + n) a c := by
47
+ obtain ⟨t, ht, he⟩ := h
48
+ obtain ⟨t', ht', he'⟩ := h'
49
+ exact ⟨t+t', Nat.add_le_add ht ht', steps_trans he he'⟩
50
+
51
+ theorem Within.head {α : Type*} {f : α → Option α} {n : ℕ} {a b c : α}
52
+ (h : f a = some b) (h' : Within f n b c) : Within f (n + 1) a c := by
53
+ obtain ⟨t, ht, he⟩ := h'
54
+ exact ⟨t+1, Nat.add_le_add_right ht 1, steps_head h he⟩
55
+
56
+ theorem within_one {α : Type*} {f : α → Option α} {a b : α}
57
+ (h : f a = some b) : Within f 1 a b := (steps_one h).within
58
+
59
+ end MinUncut.Costed
60
+
61
+ namespace Turing.PartrecToTM2
62
+ open scoped _root_.Turing _root_.Turing.PartrecToTM2
63
+ open Function
64
+ open MinUncut.Costed
65
+ open _root_.Turing.PartrecToTM2.K'
66
+
67
+ theorem move_steps {p k₁ k₂ q s L₁ o L₂} {S : _root_.Turing.PartrecToTM2.K' → List _root_.Turing.PartrecToTM2.Γ'} (h₁ : k₁ ≠ k₂)
68
+ (e : _root_.Turing.PartrecToTM2.splitAtPred p (S k₁) = (L₁, o, L₂)) :
69
+ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (L₁.length + 1) ⟨some (_root_.Turing.PartrecToTM2.Λ'.move p k₁ k₂ q), s, S⟩
70
+ ⟨some q, o, update (update S k₁ L₂) k₂ (L₁.reverseAux (S k₂))⟩ := by
71
+ induction L₁ generalizing S s with
72
+ | nil =>
73
+ rw [(_ : [].reverseAux _ = _), Function.update_eq_self]
74
+ swap
75
+ · rw [Function.update_of_ne h₁.symm, List.reverseAux_nil]
76
+ apply steps_one
77
+ simp only [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.tr_move, _root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux, Option.elim]
78
+ grind [_root_.Turing.PartrecToTM2.splitAtPred.eq_def]
79
+ | cons a L₁ IH =>
80
+ refine steps_head rfl ?_
81
+ rw [_root_.Turing.PartrecToTM2.tr]; simp only [_root_.Turing.PartrecToTM2.pop', Option.elim, _root_.Turing.TM2.stepAux, _root_.Turing.PartrecToTM2.push']
82
+ rcases e₁ : S k₁ with - | ⟨a', Sk⟩ <;> rw [e₁, _root_.Turing.PartrecToTM2.splitAtPred] at e
83
+ · cases e
84
+ cases e₂ : p a' <;> simp only [e₂, cond] at e
85
+ swap
86
+ · cases e
87
+ rcases e₃ : _root_.Turing.PartrecToTM2.splitAtPred p Sk with ⟨_, _, _⟩
88
+ rw [e₃] at e
89
+ cases e
90
+ simp only [List.head?_cons, e₂, List.tail_cons, Bool.cond_false]
91
+ convert! @IH _ (update (update S k₁ Sk) k₂ (a :: S k₂)) _ using 2 <;>
92
+ simp [Function.update_of_ne, h₁, h₁.symm, e₃, List.reverseAux]
93
+ simp [Function.update_comm h₁.symm]
94
+
95
+ theorem clear_steps {p k q s L₁ o L₂} {S : _root_.Turing.PartrecToTM2.K' → List _root_.Turing.PartrecToTM2.Γ'}
96
+ (e : _root_.Turing.PartrecToTM2.splitAtPred p (S k) = (L₁, o, L₂)) :
97
+ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (L₁.length + 1) ⟨some (_root_.Turing.PartrecToTM2.Λ'.clear p k q), s, S⟩
98
+ ⟨some q, o, update S k L₂⟩ := by
99
+ induction L₁ generalizing S s with
100
+ | nil =>
101
+ apply steps_one
102
+ simp only [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.tr_clear, _root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux]
103
+ grind [_root_.Turing.PartrecToTM2.splitAtPred.eq_def]
104
+ | cons a L₁ IH =>
105
+ refine steps_head rfl ?_
106
+ rw [_root_.Turing.PartrecToTM2.tr]; simp only [_root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux, Option.elim]
107
+ rcases e₁ : S k with - | ⟨a', Sk⟩ <;> rw [e₁, _root_.Turing.PartrecToTM2.splitAtPred] at e
108
+ · cases e
109
+ cases e₂ : p a' <;> simp only [e₂, cond] at e
110
+ swap
111
+ · cases e
112
+ rcases e₃ : _root_.Turing.PartrecToTM2.splitAtPred p Sk with ⟨_, _, _⟩
113
+ rw [e₃] at e
114
+ cases e
115
+ simp only [List.head?_cons, e₂, List.tail_cons, Bool.cond_false]
116
+ convert! @IH _ (update S k Sk) _ using 2 <;> simp [e₃]
117
+
118
+ theorem unrev_steps {q s} {S : _root_.Turing.PartrecToTM2.K' → List _root_.Turing.PartrecToTM2.Γ'} :
119
+ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) ((S rev).length + 1) ⟨some (_root_.Turing.PartrecToTM2.unrev q), s, S⟩
120
+ ⟨some q, none, update (update S rev []) main (List.reverseAux (S rev) (S main))⟩ :=
121
+ move_steps (by decide) (_root_.Turing.PartrecToTM2.splitAtPred_false _)
122
+
123
+ theorem copy_steps (q s a b c d) :
124
+ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (b.length + 1) ⟨some (_root_.Turing.PartrecToTM2.Λ'.copy q), s, _root_.Turing.PartrecToTM2.K'.elim a b c d⟩
125
+ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (List.reverseAux b a) [] c (List.reverseAux b d)⟩ := by
126
+ induction b generalizing a d s with
127
+ | nil =>
128
+ apply steps_one
129
+ simp [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.tr, _root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux]
130
+ | cons x b IH =>
131
+ refine steps_head rfl ?_
132
+ rw [_root_.Turing.PartrecToTM2.tr]
133
+ simp only [_root_.Turing.TM2.stepAux, elim_rev, List.head?_cons, Option.isSome_some,
134
+ List.tail_cons, elim_update_rev, elim_main, elim_update_main,
135
+ elim_stack, elim_update_stack, Bool.cond_true, List.reverseAux_cons, _root_.Turing.PartrecToTM2.pop', _root_.Turing.PartrecToTM2.push']
136
+ exact IH _ _ _
137
+
138
+ theorem move₂_steps {p k₁ k₂ q s L₁ o L₂} {S : _root_.Turing.PartrecToTM2.K' → List _root_.Turing.PartrecToTM2.Γ'}
139
+ (h₁ : k₁ ≠ rev ∧ k₂ ≠ rev ∧ k₁ ≠ k₂) (h₂ : S rev = [])
140
+ (e : _root_.Turing.PartrecToTM2.splitAtPred p (S k₁) = (L₁, o, L₂)) :
141
+ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2 * L₁.length + 3) ⟨some (_root_.Turing.PartrecToTM2.move₂ p k₁ k₂ q), s, S⟩
142
+ ⟨some q, none, update (update S k₁ (o.elim id List.cons L₂)) k₂ (L₁ ++ S k₂)⟩ := by
143
+ have heq : 2 * L₁.length + 3 = (L₁.length + 1) + ((L₁.length + 1) + 1) := by omega
144
+ rw [heq]
145
+ refine steps_trans (move_steps h₁.1 e) (steps_head rfl ?_)
146
+ cases o <;> rw [_root_.Turing.PartrecToTM2.tr]
147
+ <;> simp only [id, _root_.Turing.TM2.stepAux, Option.isSome, Bool.cond_true, Bool.cond_false, Option.elim]
148
+ · convert! move_steps h₁.2.1.symm (_root_.Turing.PartrecToTM2.splitAtPred_false _) using 2
149
+ · simp [Function.update_self, List.reverseAux_eq, h₂]
150
+ simp only [Function.update_comm h₁.1, Function.update_idem]
151
+ rw [show update S rev [] = S by rw [← h₂, Function.update_eq_self]]
152
+ simp only [Function.update_of_ne h₁.2.2.symm, Function.update_of_ne h₁.2.1,
153
+ Function.update_of_ne h₁.1.symm, List.reverseAux_eq, h₂, Function.update_self,
154
+ List.append_nil, List.reverse_reverse]
155
+ · simp only [Option.getD_some]
156
+ convert! move_steps h₁.2.1.symm (_root_.Turing.PartrecToTM2.splitAtPred_false _) using 2
157
+ · simp [Function.update_self, Function.update_of_ne h₁.1.symm, List.reverseAux_eq, h₂]
158
+ simp only [h₂, Function.update_comm h₁.1, List.reverseAux_eq, Function.update_self,
159
+ List.append_nil, Function.update_idem]
160
+ rw [show update S rev [] = S by rw [← h₂, Function.update_eq_self]]
161
+ simp only [Function.update_of_ne h₁.1.symm, Function.update_of_ne h₁.2.2.symm,
162
+ Function.update_of_ne h₁.2.1, Function.update_self, List.reverse_reverse]
163
+
164
+ theorem head_main_steps {q s L} {c d : List _root_.Turing.PartrecToTM2.Γ'} :
165
+ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2*(_root_.Turing.PartrecToTM2.trNat L.headI).length+(_root_.Turing.PartrecToTM2.trList L.tail).length+6)
166
+ ⟨some (_root_.Turing.PartrecToTM2.head main q), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList L) [] c d⟩
167
+ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList [L.headI]) [] c d⟩ := by
168
+ let o : Option _root_.Turing.PartrecToTM2.Γ' := List.casesOn L none fun _ _ => some _root_.Turing.PartrecToTM2.Γ'.cons
169
+ have heq : 2*(_root_.Turing.PartrecToTM2.trNat L.headI).length+(_root_.Turing.PartrecToTM2.trList L.tail).length+6 =
170
+ ((_root_.Turing.PartrecToTM2.trNat L.headI).length+1) +
171
+ ((((_root_.Turing.PartrecToTM2.trList L.tail).length+1)+((_root_.Turing.PartrecToTM2.trNat L.headI).length+2)+1)+1) := by omega
172
+ rw [heq]
173
+ refine steps_trans
174
+ (move_steps (by decide)
175
+ (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ (_root_.Turing.PartrecToTM2.trNat L.headI) o (_root_.Turing.PartrecToTM2.trList L.tail) (_root_.Turing.PartrecToTM2.trNat_natEnd _) ?_))
176
+ (steps_head rfl (steps_head rfl ?_))
177
+ · cases L <;> simp [o]
178
+ rw [_root_.Turing.PartrecToTM2.tr]
179
+ simp only [_root_.Turing.TM2.stepAux, elim_update_main, elim_rev, elim_update_rev,
180
+ Function.update_self, _root_.Turing.PartrecToTM2.trList]
181
+ rw [ite_eq_right (show o ≠ some _root_.Turing.PartrecToTM2.Γ'.consₗ by cases L <;> simp [o])]
182
+ refine steps_trans (clear_steps (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ _ none [] ?_ ⟨rfl,rfl⟩)) ?_
183
+ · exact fun x h => Bool.decide_false (_root_.Turing.PartrecToTM2.trList_ne_consₗ _ _ h)
184
+ simpa [List.reverseAux_eq] using
185
+ (unrev_steps (q := q) (s := none) (S := _root_.Turing.PartrecToTM2.K'.elim [] (_root_.Turing.PartrecToTM2.Γ'.cons :: (_root_.Turing.PartrecToTM2.trNat L.headI).reverse) c d))
186
+
187
+ theorem head_stack_time {q s L₁ L₂ L₃} :
188
+ Within (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2*(_root_.Turing.PartrecToTM2.trList L₂).length+6)
189
+ ⟨some (_root_.Turing.PartrecToTM2.head stack q), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList L₁) [] [] (_root_.Turing.PartrecToTM2.trList L₂ ++ _root_.Turing.PartrecToTM2.Γ'.consₗ :: L₃)⟩
190
+ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList (L₂.headI :: L₁)) [] [] L₃⟩ := by
191
+ rcases L₂ with - | ⟨a, L₂⟩
192
+ · have h : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (1+(2+1+1))
193
+ ⟨some (_root_.Turing.PartrecToTM2.head stack q), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList L₁) [] [] (_root_.Turing.PartrecToTM2.trList [] ++ _root_.Turing.PartrecToTM2.Γ'.consₗ :: L₃)⟩
194
+ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList ([].headI :: L₁)) [] [] L₃⟩ := by
195
+ refine steps_trans
196
+ (move_steps (by decide)
197
+ (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ [] (some _root_.Turing.PartrecToTM2.Γ'.consₗ) L₃ (by rintro _ ⟨⟩) ⟨rfl,rfl⟩))
198
+ (steps_head rfl (steps_head rfl ?_))
199
+ rw [_root_.Turing.PartrecToTM2.tr]
200
+ simp only [_root_.Turing.TM2.stepAux, ite_true, id_eq, _root_.Turing.PartrecToTM2.trList, List.nil_append,
201
+ elim_update_stack, elim_rev, List.reverseAux_nil, elim_update_rev,
202
+ Function.update_self, List.headI_nil, _root_.Turing.PartrecToTM2.trNat_default]
203
+ convert! unrev_steps using 2 <;> simp
204
+ exact h.within.mono (by simp)
205
+ · have h : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr)
206
+ (((_root_.Turing.PartrecToTM2.trNat a).length+1)+((((_root_.Turing.PartrecToTM2.trList L₂).length+1)+((_root_.Turing.PartrecToTM2.trNat a).length+2)+1)+1))
207
+ ⟨some (_root_.Turing.PartrecToTM2.head stack q), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList L₁) [] [] (_root_.Turing.PartrecToTM2.trList (a::L₂) ++ _root_.Turing.PartrecToTM2.Γ'.consₗ :: L₃)⟩
208
+ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList ((a::L₂).headI :: L₁)) [] [] L₃⟩ := by
209
+ refine steps_trans
210
+ (move_steps (by decide)
211
+ (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ (_root_.Turing.PartrecToTM2.trNat a) (some _root_.Turing.PartrecToTM2.Γ'.cons) (_root_.Turing.PartrecToTM2.trList L₂ ++ _root_.Turing.PartrecToTM2.Γ'.consₗ :: L₃)
212
+ (_root_.Turing.PartrecToTM2.trNat_natEnd _) ⟨rfl, by simp⟩))
213
+ (steps_head rfl (steps_head rfl ?_))
214
+ simp only [_root_.Turing.PartrecToTM2.trList, List.append_assoc,
215
+ List.cons_append, elim_update_stack, elim_rev, elim_update_rev,
216
+ Function.update_self, List.headI_cons]
217
+ refine steps_trans
218
+ (clear_steps
219
+ (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ (_root_.Turing.PartrecToTM2.trList L₂) (some _root_.Turing.PartrecToTM2.Γ'.consₗ) L₃
220
+ (fun x h => Bool.decide_false (_root_.Turing.PartrecToTM2.trList_ne_consₗ _ _ h)) ⟨rfl, by simp⟩)) ?_
221
+ simpa [List.reverseAux_eq] using
222
+ (unrev_steps (q := q) (s := some _root_.Turing.PartrecToTM2.Γ'.consₗ) (S := _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList L₁) (_root_.Turing.PartrecToTM2.Γ'.cons :: (_root_.Turing.PartrecToTM2.trNat a).reverse) [] L₃))
223
+ exact h.within.mono (by simp only [_root_.Turing.PartrecToTM2.trList, List.length_append, List.length_cons]; omega)
224
+
225
+ theorem succ_time {q s n} {c d : List _root_.Turing.PartrecToTM2.Γ'} :
226
+ Within (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2*(_root_.Turing.PartrecToTM2.trNat n).length+2)
227
+ ⟨some (_root_.Turing.PartrecToTM2.Λ'.succ q), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList [n]) [] c d⟩
228
+ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList [n.succ]) [] c d⟩ := by
229
+ simp only [_root_.Turing.PartrecToTM2.trList, _root_.Turing.PartrecToTM2.trNat.eq_1, Nat.cast_succ, Num.add_one]
230
+ rcases (n : Num) with - | a
231
+ · have h : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (1+1)
232
+ ⟨some (_root_.Turing.PartrecToTM2.Λ'.succ q), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trNum Num.zero ++ _root_.Turing.PartrecToTM2.Γ'.cons :: _root_.Turing.PartrecToTM2.trList []) [] c d⟩
233
+ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trNum (Num.succ Num.zero) ++ _root_.Turing.PartrecToTM2.Γ'.cons :: _root_.Turing.PartrecToTM2.trList []) [] c d⟩ := by
234
+ refine steps_head rfl ?_
235
+ convert! (unrev_steps (q := q) (s := some _root_.Turing.PartrecToTM2.Γ'.cons) (S := _root_.Turing.PartrecToTM2.K'.elim [_root_.Turing.PartrecToTM2.Γ'.bit1, _root_.Turing.PartrecToTM2.Γ'.cons] [] c d)) using 1 <;> simp <;> rfl
236
+ exact h.within
237
+ simp only [_root_.Turing.PartrecToTM2.trNum, Num.succ, Num.succ']
238
+ have hpref : ∀ l₁, ∃ l₁' l₂' s' t,
239
+ List.reverseAux l₁ (_root_.Turing.PartrecToTM2.trPosNum a.succ) = List.reverseAux l₁' l₂' ∧
240
+ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) t ⟨some q.succ, s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trPosNum a ++ [_root_.Turing.PartrecToTM2.Γ'.cons]) l₁ c d⟩
241
+ ⟨some (_root_.Turing.PartrecToTM2.unrev q), s', _root_.Turing.PartrecToTM2.K'.elim (l₂' ++ [_root_.Turing.PartrecToTM2.Γ'.cons]) l₁' c d⟩ ∧
242
+ t ≤ (_root_.Turing.PartrecToTM2.trPosNum a).length+1 ∧ l₁'.length ≤ l₁.length+(_root_.Turing.PartrecToTM2.trPosNum a).length := by
243
+ induction a generalizing s with intro l₁
244
+ | one =>
245
+ refine ⟨_root_.Turing.PartrecToTM2.Γ'.bit0::l₁, [_root_.Turing.PartrecToTM2.Γ'.bit1], some _root_.Turing.PartrecToTM2.Γ'.cons, 2, rfl,
246
+ steps_head rfl (steps_one ?_), by simp [_root_.Turing.PartrecToTM2.trPosNum], by simp [_root_.Turing.PartrecToTM2.trPosNum]⟩
247
+ simp [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.trPosNum]
248
+ | bit1 m IH =>
249
+ obtain ⟨l₁',l₂',s',t,e,h,ht,hl⟩ := IH (_root_.Turing.PartrecToTM2.Γ'.bit0::l₁)
250
+ refine ⟨l₁',l₂',s',t+1,e,steps_head ?_ h,?_,?_⟩
251
+ · simp [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.trPosNum]
252
+ rfl
253
+ · simp only [_root_.Turing.PartrecToTM2.trPosNum,List.length_cons]; omega
254
+ · simp only [_root_.Turing.PartrecToTM2.trPosNum,List.length_cons] at *; omega
255
+ | bit0 m _ =>
256
+ refine ⟨l₁, _, some _root_.Turing.PartrecToTM2.Γ'.bit0, 1, rfl, steps_one ?_, by simp [_root_.Turing.PartrecToTM2.trPosNum], by simp [_root_.Turing.PartrecToTM2.trPosNum]⟩
257
+ simp only [_root_.Turing.TM2.step]; rw [_root_.Turing.PartrecToTM2.tr]
258
+ simp only [_root_.Turing.TM2.stepAux, _root_.Turing.PartrecToTM2.pop', elim_main, elim_update_main,
259
+ elim_rev, elim_update_rev, Function.update_self]
260
+ rfl
261
+ obtain ⟨l₁',l₂',s',t,e,h,ht,hl⟩ := hpref []
262
+ simp only [List.reverseAux_nil] at e
263
+ have hu : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (l₁'.length+1)
264
+ ⟨some (_root_.Turing.PartrecToTM2.unrev q), s', _root_.Turing.PartrecToTM2.K'.elim (l₂' ++ [_root_.Turing.PartrecToTM2.Γ'.cons]) l₁' c d⟩
265
+ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trPosNum a.succ ++ [_root_.Turing.PartrecToTM2.Γ'.cons]) [] c d⟩ := by
266
+ convert! unrev_steps using 2 <;> simp [e,List.reverseAux_eq]
267
+ exact (steps_trans h hu).within.mono (by simp only [List.length_nil, zero_add] at hl; omega)
268
+
269
+ theorem pred_time (q₁ q₂ s v) (c d : List _root_.Turing.PartrecToTM2.Γ') : ∃ s',
270
+ Within (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2*(_root_.Turing.PartrecToTM2.trList v).length+3)
271
+ ⟨some (_root_.Turing.PartrecToTM2.Λ'.pred q₁ q₂), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList v) [] c d⟩
272
+ (v.headI.rec ⟨some q₁, s', _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList v.tail) [] c d⟩ fun n _ =>
273
+ ⟨some q₂, s', _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList (n::v.tail)) [] c d⟩) := by
274
+ rcases v with (_ | ⟨_ | n, v⟩)
275
+ · refine ⟨none, (within_one ?_).mono (by simp)⟩
276
+ simp [_root_.Turing.TM2.step]
277
+ · refine ⟨some _root_.Turing.PartrecToTM2.Γ'.cons, (within_one ?_).mono (by simp)⟩
278
+ simp [_root_.Turing.TM2.step]
279
+ refine ⟨none, ?_⟩
280
+ simp only [_root_.Turing.PartrecToTM2.trList, _root_.Turing.PartrecToTM2.trNat.eq_1, _root_.Turing.PartrecToTM2.trNum, Nat.cast_succ, Num.add_one, Num.succ,
281
+ List.tail_cons, List.headI_cons]
282
+ rcases (n : Num) with - | a
283
+ · simp only [_root_.Turing.PartrecToTM2.trPosNum, Num.succ', List.singleton_append, List.nil_append]
284
+ have h : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (1+1)
285
+ ⟨some (_root_.Turing.PartrecToTM2.Λ'.pred q₁ q₂), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.Γ'.bit1::_root_.Turing.PartrecToTM2.Γ'.cons::_root_.Turing.PartrecToTM2.trList v) [] c d⟩
286
+ ⟨some q₂, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.Γ'.cons::_root_.Turing.PartrecToTM2.trList v) [] c d⟩ := by
287
+ refine steps_head rfl ?_
288
+ rw [_root_.Turing.PartrecToTM2.tr]; simp only [_root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux]
289
+ convert! unrev_steps using 2 <;> simp
290
+ exact h.within.mono (by simp)
291
+ simp only [Num.succ']
292
+ have hpref : ∀ l₁, ∃ l₁' l₂' s' t,
293
+ List.reverseAux l₁ (_root_.Turing.PartrecToTM2.trPosNum a) = List.reverseAux l₁' l₂' ∧
294
+ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) t
295
+ ⟨some (q₁.pred q₂), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trPosNum a.succ ++ _root_.Turing.PartrecToTM2.Γ'.cons :: _root_.Turing.PartrecToTM2.trList v) l₁ c d⟩
296
+ ⟨some (_root_.Turing.PartrecToTM2.unrev q₂), s', _root_.Turing.PartrecToTM2.K'.elim (l₂' ++ _root_.Turing.PartrecToTM2.Γ'.cons :: _root_.Turing.PartrecToTM2.trList v) l₁' c d⟩ ∧
297
+ t ≤ (_root_.Turing.PartrecToTM2.trPosNum a.succ).length+1 ∧ l₁'.length ≤ l₁.length+(_root_.Turing.PartrecToTM2.trPosNum a.succ).length := by
298
+ induction a generalizing s with intro l₁
299
+ | one =>
300
+ refine ⟨_root_.Turing.PartrecToTM2.Γ'.bit1::l₁, [], some _root_.Turing.PartrecToTM2.Γ'.cons, 2, rfl,
301
+ steps_head rfl (steps_one ?_), by simp [_root_.Turing.PartrecToTM2.trPosNum,PosNum.succ], by simp [_root_.Turing.PartrecToTM2.trPosNum,PosNum.succ]⟩
302
+ simp [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.trPosNum, show PosNum.one.succ = PosNum.one.bit0 from rfl]
303
+ | bit1 m IH =>
304
+ obtain ⟨l₁',l₂',s',t,e,h,ht,hl⟩ := IH (some _root_.Turing.PartrecToTM2.Γ'.bit0) (_root_.Turing.PartrecToTM2.Γ'.bit1::l₁)
305
+ refine ⟨l₁',l₂',s',t+1,e,steps_head ?_ h,?_,?_⟩
306
+ · simp [_root_.Turing.TM2.step]
307
+ rfl
308
+ · simp only [PosNum.succ,_root_.Turing.PartrecToTM2.trPosNum,List.length_cons]; omega
309
+ · simp only [PosNum.succ,_root_.Turing.PartrecToTM2.trPosNum,List.length_cons] at *; omega
310
+ | bit0 m _ =>
311
+ obtain ⟨a,l,e,h⟩ : ∃ a l, _root_.Turing.PartrecToTM2.trPosNum m=a::l ∧ _root_.Turing.PartrecToTM2.natEnd a=false := by
312
+ cases m <;> refine ⟨_,_,rfl,rfl⟩
313
+ refine ⟨_root_.Turing.PartrecToTM2.Γ'.bit0::l₁, _, some a, 1, rfl, steps_one ?_,
314
+ by simp [PosNum.succ,_root_.Turing.PartrecToTM2.trPosNum], by simp [PosNum.succ,_root_.Turing.PartrecToTM2.trPosNum]⟩
315
+ simp [_root_.Turing.TM2.step,_root_.Turing.PartrecToTM2.trPosNum,PosNum.succ,e,h,show some _root_.Turing.PartrecToTM2.Γ'.bit1 ≠ some _root_.Turing.PartrecToTM2.Γ'.bit0 by decide,
316
+ Option.getD,-_root_.Turing.PartrecToTM2.natEnd]
317
+ simp [_root_.Turing.PartrecToTM2.natEnd]
318
+ obtain ⟨l₁',l₂',s',t,e,h,ht,hl⟩ := hpref []
319
+ simp only [List.reverseAux_nil] at e
320
+ have hu : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (l₁'.length+1)
321
+ ⟨some (_root_.Turing.PartrecToTM2.unrev q₂), s', _root_.Turing.PartrecToTM2.K'.elim (l₂' ++ _root_.Turing.PartrecToTM2.Γ'.cons :: _root_.Turing.PartrecToTM2.trList v) l₁' c d⟩
322
+ ⟨some q₂, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trPosNum a ++ _root_.Turing.PartrecToTM2.Γ'.cons :: _root_.Turing.PartrecToTM2.trList v) [] c d⟩ := by
323
+ convert! unrev_steps using 2 <;> simp [e,List.reverseAux_eq]
324
+ exact (steps_trans h hu).within.mono (by
325
+ simp only [List.length_nil,zero_add] at hl
326
+ simp only [List.length_append,List.length_cons]; omega)
327
+
328
+ end Turing.PartrecToTM2
329
+
330
+ end
331
+
332
+ namespace MinUncut.Costed.WordTransducer
333
+ open _root_.Turing Function
334
+
335
+ inductive Tape | input | work | output deriving DecidableEq
336
+
337
+ protected abbrev Tape.enumList : List Tape := [.input, .work, .output]
338
+
339
+ protected theorem Tape.enumList_getElem?_ctorIdx_eq (x : Tape) :
340
+ Tape.enumList[x.ctorIdx]? = some x := by
341
+ cases x <;> rfl
342
+
343
+ protected theorem Tape.enumList_nodup : Tape.enumList.Nodup := by decide
344
+
345
+ instance : Fintype Tape where
346
+ elems := ⟨Tape.enumList, Tape.enumList_nodup⟩
347
+ complete x := by cases x <;> decide
348
+
349
+ def Alphabet (A B : Type) : Tape → Type
350
+ | .input => A
351
+ | .work | .output => B
352
+
353
+ def tapes {A B : Type} (input : List A) (work output : List B) :
354
+ ∀ k,List (Alphabet A B k)
355
+ | .input => input
356
+ | .work => work
357
+ | .output => output
358
+
359
+ @[simp] lemma update_input {A B : Type} (i i' : List A) (w o : List B) :
360
+ update (tapes i w o) .input i'=tapes i' w o := by
361
+ funext k
362
+ cases k <;> simp only [tapes] <;> rfl
363
+ @[simp] lemma update_work {A B : Type} (i : List A) (w w' o : List B) :
364
+ update (tapes i w o) .work w'=tapes i w' o := by
365
+ funext k; cases k <;> rfl
366
+ @[simp] lemma update_output {A B : Type} (i : List A) (w o o' : List B) :
367
+ update (tapes i w o) .output o'=tapes i w o' := by
368
+ funext k; cases k <;> rfl
369
+
370
+ def pushWord {K Λ σ : Type} {Γ : K → Type} (dst : K) :
371
+ List (Γ dst) → TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ σ
372
+ | [], q => q
373
+ | a::w, q => .push dst (fun _ => a) (pushWord dst w q)
374
+
375
+ lemma pushWord_aux {K Λ σ : Type} {Γ : K → Type} [DecidableEq K] (dst : K)
376
+ (w : List (Γ dst)) (q : TM2.Stmt Γ Λ σ) (s : σ) (st : ∀ k,List (Γ k)) :
377
+ TM2.stepAux (pushWord dst w q) s st=
378
+ TM2.stepAux q s (update st dst (w.reverse++st dst)) := by
379
+ induction w generalizing st with
380
+ | nil => simp [pushWord]
381
+ | cons a w ih =>
382
+ simp only [pushWord,TM2.stepAux,ih,update_self,update_idem,
383
+ List.reverse_cons,List.append_assoc,List.singleton_append]
384
+
385
+ variable {A B Q : Type}
386
+ inductive Label (Q A : Type) | read | emit (q : Q) (a : A) | reverse
387
+ deriving DecidableEq, Fintype
388
+ abbrev State (Q A B : Type) := Q × Option A × Option B
389
+
390
+ def output (next : Q → A → Q) (emit : Q → A → List B) : Q → List A → List B
391
+ | _, [] => []
392
+ | q,a::v => emit q a ++ output next emit (next q a) v
393
+
394
+ def program [Inhabited A] [Inhabited B] (initial : Q)
395
+ (next : Q → A → Q) (emit : Q → A → List B) :
396
+ Label Q A → TM2.Stmt (Alphabet A B) (Label Q A) (State Q A B)
397
+ | .read => .pop .input (fun s a => (s.1,a,s.2.2))
398
+ (.branch (fun s => s.2.1.isSome)
399
+ (.goto fun s => .emit s.1 (s.2.1.getD default))
400
+ (.load (fun _ => (initial,none,none)) (.goto fun _ => .reverse)))
401
+ | .emit q a => .load (fun _ => (next q a,none,none))
402
+ (pushWord .work (emit q a) (.goto fun _ => .read))
403
+ | .reverse => .pop .work (fun s b => (s.1,s.2.1,b))
404
+ (.branch (fun s => s.2.2.isSome)
405
+ (.push .output (fun s => s.2.2.getD default) (.goto fun _ => .reverse))
406
+ (.load (fun _ => (initial,none,none)) .halt))
407
+
408
+ def machine [Fintype A] [Fintype B] [Fintype Q] [Inhabited A] [Inhabited B]
409
+ (initial : Q) (next : Q → A → Q) (emit : Q → A → List B) : FinTM2 where
410
+ K := Tape
411
+ k₀ := .input
412
+ k₁ := .output
413
+ Γ := Alphabet A B
414
+ Γk₀Fin := inferInstanceAs (Fintype A)
415
+ Λ := Label Q A
416
+ main := .read
417
+ σ := State Q A B
418
+ initialState := (initial,none,none)
419
+ m := program initial next emit
420
+
421
+ lemma finiteAlphabet [Fintype A] [Fintype B] [Fintype Q] [Inhabited A] [Inhabited B]
422
+ (initial : Q) (next : Q → A → Q) (emit : Q → A → List B)
423
+ (k : (machine initial next emit).K) : Finite ((machine initial next emit).Γ k) := by
424
+ cases k <;> dsimp [machine,Alphabet] <;> infer_instance
425
+
426
+ variable [Inhabited A] [Inhabited B]
427
+
428
+ lemma reverse_steps (initial : Q) (next : Q → A → Q) (emit : Q → A → List B)
429
+ (w o : List B) (s : State Q A B) :
430
+ Steps (TM2.step (program initial next emit)) (w.length+1)
431
+ ⟨some .reverse,s,tapes [] w o⟩
432
+ ⟨none,(initial,none,none),tapes [] [] (w.reverse++o)⟩ := by
433
+ induction w generalizing s o with
434
+ | nil =>
435
+ apply steps_one
436
+ simp only [TM2.step, program]
437
+ exact congrArg (fun st => (some ⟨none, (initial, none, none), st⟩ :
438
+ Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B))))
439
+ (update_work (A := A) [] [] [] o)
440
+ | cons b w ih =>
441
+ have h : TM2.step (program initial next emit)
442
+ ⟨some .reverse,s,tapes [] (b::w) o⟩=
443
+ some ⟨some .reverse,(s.1,s.2.1,some b),tapes [] w (b::o)⟩ := by
444
+ have hwork := update_work (A := A) [] (b :: w) w o
445
+ have hout := update_output (A := A) [] w o (b :: o)
446
+ have ht := (congrArg (fun st => update st Tape.output (b :: o)) hwork).trans hout
447
+ exact congrArg (fun st => (some ⟨some .reverse, (s.1, s.2.1, some b), st⟩ :
448
+ Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B)))) ht
449
+ simpa only [List.length_cons,List.reverse_cons,List.append_assoc,List.singleton_append]
450
+ using steps_head h (ih (b::o) (s.1,s.2.1,some b))
451
+
452
+ lemma emit_steps (initial q : Q) (next : Q → A → Q) (emit : Q → A → List B)
453
+ (a : A) (v : List A) (w : List B) :
454
+ Steps (TM2.step (program initial next emit)) 2
455
+ ⟨some .read,(q,none,none),tapes (a::v) w []⟩
456
+ ⟨some .read,(next q a,none,none),tapes v ((emit q a).reverse++w) []⟩ := by
457
+ apply steps_head (b := ⟨some (.emit q a),(q,some a,none),tapes v w []⟩)
458
+ · exact congrArg (fun st => (some ⟨some (.emit q a), (q, some a, none), st⟩ :
459
+ Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B))))
460
+ (update_input (a :: v) v w [])
461
+ · apply steps_one
462
+ have hp := pushWord_aux (Γ := Alphabet A B) (Λ := Label Q A) (σ := State Q A B)
463
+ Tape.work (emit q a) (.goto fun _ => .read) (next q a, none, none) (tapes v w [])
464
+ exact (congrArg some hp).trans
465
+ (congrArg (fun st => (some ⟨some .read, (next q a, none, none), st⟩ :
466
+ Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B))))
467
+ (update_work v w ((emit q a).reverse ++ w) []))
468
+
469
+ lemma read_steps (initial q : Q) (next : Q → A → Q) (emit : Q → A → List B)
470
+ (v : List A) (w : List B) :
471
+ Steps (TM2.step (program initial next emit)) (2*v.length+1)
472
+ ⟨some .read,(q,none,none),tapes v w []⟩
473
+ ⟨some .reverse,(initial,none,none),tapes [] ((output next emit q v).reverse++w) []⟩ := by
474
+ induction v generalizing q w with
475
+ | nil =>
476
+ apply steps_one
477
+ exact congrArg (fun st => (some ⟨some .reverse, (initial, none, none), st⟩ :
478
+ Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B))))
479
+ (update_input (A := A) [] [] w [])
480
+ | cons a v ih =>
481
+ have ht := steps_trans (emit_steps initial q next emit a v w)
482
+ (ih (next q a) ((emit q a).reverse++w))
483
+ convert ht using 1 <;> simp [output,List.reverse_append,List.append_assoc]
484
+ omega
485
+
486
+ variable [Fintype A] [Fintype B] [Fintype Q]
487
+
488
+ def outputsInTime (initial : Q) (next : Q → A → Q) (emit : Q → A → List B) (v : List A) :
489
+ TM2OutputsInTime (machine initial next emit) v (some (output next emit initial v))
490
+ (2*v.length+(output next emit initial v).length+2) := by
491
+ have h₁ := read_steps initial initial next emit v []
492
+ simp only [List.append_nil] at h₁
493
+ have h := steps_trans h₁
494
+ (reverse_steps initial next emit ((output next emit initial v).reverse) [] (initial,none,none))
495
+ have hi : initList (machine initial next emit) v=
496
+ ⟨some .read,(initial,none,none),tapes v [] []⟩ := by
497
+ change TM2.Cfg.mk _ _ _=TM2.Cfg.mk _ _ _
498
+ congr 1
499
+ funext k; cases k <;> rfl
500
+ have ho : haltList (machine initial next emit) (output next emit initial v)=
501
+ ⟨none,(initial,none,none),tapes [] [] (output next emit initial v)⟩ := by
502
+ change TM2.Cfg.mk _ _ _=TM2.Cfg.mk _ _ _
503
+ congr 1
504
+ funext k; cases k <;> rfl
505
+ apply steps_timed (n := (2*v.length+1)+((output next emit initial v).reverse.length+1))
506
+ · change Steps (TM2.step (program initial next emit)) _ _ _
507
+ simp only [hi,ho,List.append_nil,List.reverse_reverse] at h ⊢
508
+ exact h
509
+ · simp only [List.length_reverse]; omega
510
+
511
+ end MinUncut.Costed.WordTransducer
512
+
513
+ namespace MinUncut.Costed
514
+ open _root_.Turing _root_.Turing.ToPartrec _root_.Turing.PartrecToTM2
515
+ _root_.OAI.Turing.PartrecToTM2 Function
516
+ open _root_.Turing.PartrecToTM2.K'
517
+
518
+ theorem head_tail_length (v : List ℕ) :
519
+ (trNat v.headI).length+(trList v.tail).length ≤ bitsize v := by
520
+ cases v <;> simp [bitsize,trList]
521
+
522
+ theorem head_length (v : List ℕ) : (trNat v.headI).length ≤ bitsize v :=
523
+ (Nat.le_add_right _ _).trans (head_tail_length v)
524
+
525
+ theorem tail_length (v : List ℕ) : bitsize v.tail ≤ bitsize v :=
526
+ (Nat.le_add_left _ _).trans (head_tail_length v)
527
+
528
+ theorem save_steps (f fs : Code) (k : Cont') (v : List ℕ) (s : Option Γ') (S : List Γ') :
529
+ Steps (TM2.step tr) (2*bitsize v+3)
530
+ ⟨some (trNormal (.cons f fs) k),s,K'.elim (trList v) [] [] S⟩
531
+ ⟨some (trNormal f (.cons₁ fs k)),none,
532
+ K'.elim (trList v) [] [] (trList v ++ Γ'.consₗ::S)⟩ := by
533
+ have he : 2*bitsize v+3=((trList v).length+1)+((trList v).length+1)+1 := by
534
+ simp only [bitsize]; omega
535
+ rw [he]
536
+ refine steps_head rfl (steps_trans (move_steps (by decide) (splitAtPred_false _)) ?_)
537
+ simp only [elim_stack,elim_update_stack,elim_update_main,elim_rev,elim_update_rev]
538
+ simpa [List.reverseAux_eq] using
539
+ (copy_steps (trNormal f (.cons₁ fs k)) none [] (trList v).reverse [] (Γ'.consₗ::S))
540
+
541
+ theorem swap_steps (fs : Code) (k : Cont') (v u : List ℕ) (s : Option Γ') (S : List Γ') :
542
+ Steps (TM2.step tr) (4*bitsize u+2*bitsize v+10)
543
+ ⟨some (Λ'.ret (.cons₁ fs k)),s,
544
+ K'.elim (trList u) [] [] (trList v ++ Γ'.consₗ::S)⟩
545
+ ⟨some (trNormal fs (.cons₂ k)),none,
546
+ K'.elim (trList v) [] [] (trList u ++ Γ'.consₗ::S)⟩ := by
547
+ have he : 4*bitsize u+2*bitsize v+10 =
548
+ (2*(trList u).length+3)+((2*(trList v).length+3)+(2*(trList u).length+3))+1 := by
549
+ simp only [bitsize]; omega
550
+ rw [he]
551
+ refine steps_head rfl (steps_trans (move₂_steps (by decide) rfl (splitAtPred_false _)) ?_)
552
+ simp only [Option.elim,id_eq,elim_update_main,elim_aux,
553
+ List.append_nil,elim_update_aux]
554
+ refine steps_trans (move₂_steps (o := some Γ'.consₗ) (L₂ := S) (by decide) rfl ?_) ?_
555
+ · exact splitAtPred_eq _ _ (trList v) (some Γ'.consₗ) S
556
+ (fun x h => Bool.decide_false (trList_ne_consₗ _ _ h)) ⟨rfl,rfl⟩
557
+ simpa only [Option.elim,List.append_nil,elim_update_stack,elim_main,
558
+ elim_update_main,id_eq,elim_update_aux,elim_aux,elim_stack] using
559
+ (move₂_steps (q := trNormal fs (.cons₂ k)) (s := none)
560
+ (p := fun _ => false) (k₁ := aux) (k₂ := stack)
561
+ (S := K'.elim (trList v) [] (trList u) (Γ'.consₗ::S))
562
+ (by decide) rfl (splitAtPred_false _))
563
+
564
+ theorem fix_done_steps (f : Code) (k : Cont') (v : List ℕ) (s : Option Γ') (S : List Γ')
565
+ (hv : v.headI=0) :
566
+ Steps (TM2.step tr) 1
567
+ ⟨some (Λ'.ret (.fix f k)),s,K'.elim (trList v) [] [] S⟩
568
+ ⟨some (Λ'.ret k),(trList v).head?,K'.elim (trList v.tail) [] [] S⟩ := by
569
+ apply steps_one
570
+ cases v with
571
+ | nil => simp [TM2.step]
572
+ | cons a v =>
573
+ simp only [List.headI_cons] at hv
574
+ subst a
575
+ simp [TM2.step]
576
+
577
+ theorem fix_more_steps (f : Code) (k : Cont') (a : ℕ) (v : List ℕ) (s : Option Γ') (S : List Γ') :
578
+ Steps (TM2.step tr) ((trNat (a+1)).length+1)
579
+ ⟨some (Λ'.ret (.fix f k)),s,K'.elim (trList ((a+1)::v)) [] [] S⟩
580
+ ⟨some (trNormal f (.fix f k)),some Γ'.cons,K'.elim (trList v) [] [] S⟩ := by
581
+ have htt : natEnd ((trList ((a+1)::v)).head?.getD default)=false ∧
582
+ (trList ((a+1)::v)).tail=(trNat (a+1)).tail ++ Γ'.cons::trList v := by
583
+ simp only [trList,trNat.eq_1,Nat.cast_succ,Num.add_one,Num.succ]
584
+ cases (a : Num).succ' <;> exact ⟨rfl,rfl⟩
585
+ have hn : (trNat (a+1)).length=(trNat (a+1)).tail.length+1 := by
586
+ simp only [trNat.eq_1,Nat.cast_succ,Num.add_one,Num.succ]
587
+ cases (a : Num).succ' <;> simp [trNum,trPosNum]
588
+ rw [hn]
589
+ refine steps_head rfl ?_
590
+ rw [tr]; simp only [TM2.stepAux,pop',elim_main,htt.1]
591
+ convert! (clear_steps (q := trNormal f (.fix f k))
592
+ (s := (trList ((a+1)::v)).head?) (k := main)
593
+ (S := K'.elim (trList ((a+1)::v)).tail [] [] S)
594
+ (splitAtPred_eq _ _ (trNat (a+1)).tail (some Γ'.cons) (trList v)
595
+ (fun x h => trNat_natEnd _ _ (List.tail_subset _ h)) ⟨rfl,htt.2⟩)) using 2 <;> simp
596
+
597
+ theorem CodeRun.compiled {c v w t} (h : CodeRun c v w t)
598
+ (k : Cont') (s : Option Γ') (S : List Γ') : ∃ s',
599
+ Within (TM2.step tr) t
600
+ ⟨some (trNormal c k),s,K'.elim (trList v) [] [] S⟩
601
+ ⟨some (Λ'.ret k),s',K'.elim (trList w) [] [] S⟩ := by
602
+ induction h generalizing k s S with
603
+ | zero v => exact ⟨s,within_one (by simp [TM2.step])⟩
604
+ | succ v =>
605
+ refine ⟨none,?_⟩
606
+ have hh := (head_main_steps (q := Λ'.succ (.ret k)) (s := s) (L := v)
607
+ (c := []) (d := S)).within.trans (succ_time (n := v.headI))
608
+ exact hh.mono (by have hv := head_tail_length v; dsimp [bitsize] at *; omega)
609
+ | tail v =>
610
+ let o : Option Γ' := List.casesOn v none fun _ _ => some Γ'.cons
611
+ refine ⟨o,?_⟩
612
+ have hh : Steps (TM2.step tr) ((trNat v.headI).length+1)
613
+ ⟨some (trNormal .tail k),s,K'.elim (trList v) [] [] S⟩
614
+ ⟨some (.ret k),o,K'.elim (trList v.tail) [] [] S⟩ := by
615
+ convert! (clear_steps (q := .ret k) (s := s) (k := main)
616
+ (S := K'.elim (trList v) [] [] S)
617
+ (splitAtPred_eq _ _ (trNat v.headI) o (trList v.tail) (trNat_natEnd _) ?_)) using 2
618
+ · simp
619
+ · dsimp [o]
620
+ cases v <;> exact ⟨rfl,rfl⟩
621
+ exact hh.within.mono (by have hv := head_length v; omega)
622
+ | @cons f fs v u w t t' hf hfs ih ih' =>
623
+ obtain ⟨s₁,h₁⟩ := ih (.cons₁ fs k) none (trList v ++ Γ'.consₗ::S)
624
+ obtain ⟨s₂,h₂⟩ := ih' (.cons₂ k) none (trList u ++ Γ'.consₗ::S)
625
+ have h₃ := (save_steps f fs k v s S).within.trans h₁
626
+ have h₄ := h₃.trans (swap_steps fs k v u s₁ S).within
627
+ have h₅ := h₄.trans h₂
628
+ have h₆ : Within (TM2.step tr) (2*bitsize u+6+1)
629
+ ⟨some (.ret (.cons₂ k)),s₂,K'.elim (trList w) [] [] (trList u ++ Γ'.consₗ::S)⟩
630
+ ⟨some (.ret k),none,K'.elim (trList (u.headI::w)) [] [] S⟩ :=
631
+ (head_stack_time (q := .ret k) (s := s₂) (L₁ := w) (L₂ := u) (L₃ := S)).head rfl
632
+ exact ⟨none,(h₅.trans h₆).mono (by omega)⟩
633
+ | @comp f g v u w t t' hg hf ih ih' =>
634
+ obtain ⟨s₁,h₁⟩ := ih (.comp f k) s S
635
+ obtain ⟨s₂,h₂⟩ := ih' k s₁ S
636
+ exact ⟨s₂,(h₁.trans (h₂.head rfl)).mono (by omega)⟩
637
+ | @caseZero f g v w t hz hf ih =>
638
+ obtain ⟨s₁,h₁⟩ := pred_time (trNormal f k) (trNormal g k) s v [] S
639
+ simp only [hz,Nat.rec_zero] at h₁
640
+ obtain ⟨s₂,h₂⟩ := ih k s₁ S
641
+ exact ⟨s₂,(h₁.trans h₂).mono (by dsimp [bitsize]; omega)⟩
642
+ | @caseSucc f g v a w t hg ih =>
643
+ obtain ⟨s₁,h₁⟩ := pred_time (trNormal f k) (trNormal g k) s ((a+1)::v) [] S
644
+ simp only [List.headI_cons,List.tail_cons] at h₁
645
+ obtain ⟨s₂,h₂⟩ := ih k s₁ S
646
+ exact ⟨s₂,(h₁.trans h₂).mono (by dsimp [bitsize]; omega)⟩
647
+ | @fixDone f v u t hf hu ih =>
648
+ obtain ⟨s₁,h₁⟩ := ih (.fix f k) s S
649
+ exact ⟨(trList u).head?,h₁.trans (fix_done_steps f k u s₁ S hu).within⟩
650
+ | @fixMore f v u a w t t' hf hr ih ih' =>
651
+ obtain ⟨s₁,h₁⟩ := ih (.fix f k) s S
652
+ obtain ⟨s₂,h₂⟩ := ih' k (some Γ'.cons) S
653
+ exact ⟨s₂,((h₁.trans (fix_more_steps f k a u s₁ S).within).trans h₂).mono
654
+ (by dsimp [bitsize]; simp only [List.length_append,List.length_cons]; omega)⟩
655
+
656
+ open _root_.Turing
657
+ namespace FiniteControl
658
+ variable {K Λ σ : Type} {Γ : K → Type} [DecidableEq K]
659
+
660
+ noncomputable def stmt (S : Finset Λ) :
661
+ (q : TM2.Stmt Γ Λ σ) → TM2.SupportsStmt S q → TM2.Stmt Γ S σ
662
+ | .push k f q, h => .push k f (stmt S q h)
663
+ | .peek k f q, h => .peek k f (stmt S q h)
664
+ | .pop k f q, h => .pop k f (stmt S q h)
665
+ | .load f q, h => .load f (stmt S q h)
666
+ | .branch f q r, h => .branch f (stmt S q h.1) (stmt S r h.2)
667
+ | .goto f, h => .goto (fun s => ⟨f s,h s⟩)
668
+ | .halt, _ => .halt
669
+
670
+ def project (S : Finset Λ) (c : TM2.Cfg Γ S σ) : TM2.Cfg Γ Λ σ :=
671
+ ⟨c.l.map Subtype.val,c.var,c.stk⟩
672
+
673
+ omit [DecidableEq K] in
674
+ lemma project_injective (S : Finset Λ) : Function.Injective (project (Γ:=Γ) (σ:=σ) S) := by
675
+ intro a b h
676
+ cases a with | mk a v A =>
677
+ cases b with | mk b w B =>
678
+ simp only [project,TM2.Cfg.mk.injEq] at h
679
+ rcases h with ⟨h,hv,hB⟩
680
+ have hab : a=b := Option.map_injective Subtype.val_injective h
681
+ cases hab; cases hv; cases hB; rfl
682
+
683
+ lemma project_aux (S : Finset Λ) (q : TM2.Stmt Γ Λ σ) (h : TM2.SupportsStmt S q)
684
+ (s : σ) (st : ∀ k,List (Γ k)) :
685
+ project S (TM2.stepAux (stmt S q h) s st)=TM2.stepAux q s st := by
686
+ induction q generalizing s st with
687
+ | push k f q ih => exact ih h _ _
688
+ | peek k f q ih => exact ih h _ _
689
+ | pop k f q ih => exact ih h _ _
690
+ | load f q ih => exact ih h _ _
691
+ | branch f q r ih ih' =>
692
+ cases he : f s <;> simp only [stmt,TM2.stepAux,he,
693
+ Bool.cond_false,Bool.cond_true] <;> first | exact ih h.1 _ _ | exact ih' h.2 _ _
694
+ | goto f => rfl
695
+ | halt => rfl
696
+
697
+ noncomputable def program (S : Finset Λ) (m : Λ → TM2.Stmt Γ Λ σ)
698
+ (h : ∀q∈S,TM2.SupportsStmt S (m q)) : S → TM2.Stmt Γ S σ :=
699
+ fun q => stmt S (m q.val) (h q q.property)
700
+
701
+ lemma project_step (S : Finset Λ) (m : Λ → TM2.Stmt Γ Λ σ)
702
+ (h : ∀q∈S,TM2.SupportsStmt S (m q)) (c : TM2.Cfg Γ S σ) :
703
+ (TM2.step (program S m h) c).map (project S)=TM2.step m (project S c) := by
704
+ rcases c with ⟨l,s,st⟩
705
+ cases l with
706
+ | none => rfl
707
+ | some q => exact congrArg some (project_aux S (m q) (h q q.property) s st)
708
+
709
+ lemma projected_iterate {α β : Type} (f : α → Option α) (g : β → Option β)
710
+ (p : α → β) (h : ∀a,(f a).map p=g (p a)) (n : ℕ) (a : Option α) :
711
+ ((fun x => x.bind f)^[n] a).map p=(fun x => x.bind g)^[n] (a.map p) := by
712
+ induction n generalizing a with
713
+ | zero => rfl
714
+ | succ n ih =>
715
+ rw [Function.iterate_succ_apply,Function.iterate_succ_apply,ih]
716
+ congr 1
717
+ cases a with
718
+ | none => rfl
719
+ | some a => exact h a
720
+
721
+ end FiniteControl
722
+ end MinUncut.Costed
723
+
724
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/TableLawPacking.lean ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Analysis.LiteralGaussian
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ noncomputable section
8
+ open scoped BigOperators
9
+ open MeasureTheory ProbabilityTheory
10
+ namespace MinUncut.FiniteGaussian
11
+ open GaussianBudget MinUncut.Inner
12
+ attribute [local instance] Classical.propDecidable
13
+ variable {m n : ℕ}
14
+
15
+ def sourceTable (σ η : ℝ) (c g : Point m n → ℝ) (l : Code m n → ℝ) :
16
+ ScoreIndex m n → Bool := fun s => if s.1 then query (c+σ•g) (η•l) s.2 else query c 0 s.2
17
+
18
+ lemma sourceTable_packed (σ η : ℝ) (c g : Point m n → ℝ) (l : Code m n → ℝ) :
19
+ sourceTable σ η c g l=thresholdTable (scoreFamily σ η) (packEquiv (c,g,l)) := by
20
+ funext s
21
+ exact (scoreFamily_packed σ η s (c,g,l)).symm
22
+
23
+ lemma table_integral_pack (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ)
24
+ (hF : ∀ t, 0≤F t ∧ F t≤1) :
25
+ (∫ c, ∫ g, ∫ l, F (sourceTable σ η c g l) ∂gauss (Code m n)
26
+ ∂gauss (Point m n) ∂gauss (Point m n))=
27
+ ∫ x, F (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) := by
28
+ have ht := tableTest_integrable (scoreFamily σ η) F hF
29
+ have hp := pack_preserving (X := Point m n) (C := Code m n)
30
+ have hi : Integrable (fun p : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) =>
31
+ F (thresholdTable (scoreFamily σ η) (packEquiv p))) (productLaw (Point m n) (Code m n)) :=
32
+ hp.integrable_comp_of_integrable ht
33
+ rw [← hp.integral_comp packEquiv.measurableEmbedding (fun x => F (thresholdTable (scoreFamily σ η) x))]
34
+ rw [integral_prod _ hi]
35
+ apply integral_congr_ae
36
+ filter_upwards [hi.prod_right_ae] with c hc
37
+ rw [integral_prod _ hc]
38
+ apply integral_congr_ae
39
+ filter_upwards [] with g
40
+ apply integral_congr_ae
41
+ filter_upwards [] with l
42
+ rw [sourceTable_packed]
43
+
44
+ lemma sourceTest_integrable (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ)
45
+ (hF : ∀ t, 0≤F t ∧ F t≤1) :
46
+ Integrable (fun p : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) =>
47
+ F (sourceTable σ η p.1 p.2.1 p.2.2)) (productLaw (Point m n) (Code m n)) := by
48
+ simp_rw [sourceTable_packed]
49
+ exact (pack_preserving (X := Point m n) (C := Code m n)).integrable_comp_of_integrable
50
+ (tableTest_integrable (scoreFamily σ η) F hF)
51
+
52
+ lemma sourceTest_inner_integrable (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ)
53
+ (hF : ∀ t, 0≤F t ∧ F t≤1) (c : Point m n → ℝ) :
54
+ Integrable (fun p : (Point m n → ℝ) × (Code m n → ℝ) =>
55
+ F (sourceTable σ η c p.1 p.2)) ((gauss (Point m n)).prod (gauss (Code m n))) := by
56
+ simp_rw [sourceTable_packed]
57
+ apply Integrable.of_bound
58
+ (((measurable_of_countable F).comp (thresholdTable_measurable (scoreFamily σ η))).comp
59
+ (packEquiv.measurable.comp (measurable_const.prodMk measurable_id))).aestronglyMeasurable 1
60
+ filter_upwards [] with p
61
+ simpa only [Function.comp_apply,id_eq,Real.norm_eq_abs,abs_of_nonneg (hF _).1]
62
+ using (hF (thresholdTable (scoreFamily σ η) (packEquiv (c,p)))).2
63
+
64
+ lemma sourceTest_outer_integrable (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ)
65
+ (hF : ∀ t, 0≤F t ∧ F t≤1) :
66
+ Integrable (fun c => ∫ g, ∫ l, F (sourceTable σ η c g l) ∂gauss (Code m n)
67
+ ∂gauss (Point m n)) (gauss (Point m n)) := by
68
+ have hi := (sourceTest_integrable σ η F hF).integral_prod_left
69
+ have he (c : Point m n → ℝ) := integral_prod
70
+ (fun p : (Point m n → ℝ) × (Code m n → ℝ) => F (sourceTable σ η c p.1 p.2))
71
+ (sourceTest_inner_integrable σ η F hF c)
72
+ change Integrable (fun c => ∫ p : (Point m n → ℝ) × (Code m n → ℝ),
73
+ F (sourceTable σ η c p.1 p.2) ∂(gauss (Point m n)).prod (gauss (Code m n)))
74
+ (gauss (Point m n)) at hi
75
+ simpa only [he] using hi
76
+
77
+ lemma table_integral_product (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ)
78
+ (hF : ∀ t, 0≤F t ∧ F t≤1) :
79
+ (∫ c, ∫ p : (Point m n → ℝ) × (Code m n → ℝ), F (sourceTable σ η c p.1 p.2)
80
+ ∂(gauss (Point m n)).prod (gauss (Code m n)) ∂gauss (Point m n))=
81
+ ∫ x, F (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) := by
82
+ rw [← table_integral_pack σ η F hF]
83
+ apply integral_congr_ae
84
+ filter_upwards [] with c
85
+ exact integral_prod _ (sourceTest_inner_integrable σ η F hF c)
86
+
87
+ end MinUncut.FiniteGaussian
88
+
89
+ end
90
+ end
91
+
92
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/TableTestFunctions.lean ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.ActualBoxBound
3
+ import OAI.Computability.MinUncut.Estimates.FourthTest
4
+ import OAI.Computability.MinUncut.Estimates.TableLawPacking
5
+
6
+ namespace OAI
7
+
8
+ section
9
+ noncomputable section
10
+ open scoped BigOperators
11
+ open MeasureTheory ProbabilityTheory
12
+ namespace MinUncut.FiniteGaussian
13
+ open GaussianBudget MinUncut.Inner
14
+ attribute [local instance] Classical.propDecidable
15
+ variable {V A V' A' : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
16
+ [AddCommGroup V'] [Module F₂ V'] [AddTorsor V' A'] [Fintype A'] {m n : ℕ}
17
+
18
+ def disagreement (b c : Bool) : ℝ := if b=c then 0 else 1
19
+
20
+ lemma disagreement_range (b c : Bool) : 0≤disagreement b c ∧ disagreement b c≤1 := by
21
+ unfold disagreement
22
+ split <;> norm_num
23
+
24
+ def firstTable (f : FoldedProof A) (B : FaceArray A m n) (t : ScoreIndex m n → Bool) : ℝ :=
25
+ disagreement (f.answer (fun a => t (false,labelCode B a)))
26
+ (f.answer (fun a => t (true,labelCode B a)))
27
+
28
+ def secondTable (f : FoldedProof A) (B C : FaceArray A m n) (t : ScoreIndex m n → Bool) : ℝ :=
29
+ disagreement (f.answer (fun a => t (true,labelCode B a)))
30
+ (f.answer (fun a => t (true,labelCode C a)))
31
+
32
+ def thirdTable (f : FoldedProof A) (B : FaceArray A m n) (z : Code m n)
33
+ (t : ScoreIndex m n → Bool) : ℝ :=
34
+ disagreement (f.answer (fun a => Function.update (fun z => t (true,z)) z true (labelCode B a)))
35
+ (f.answer (fun a => Function.update (fun z => t (true,z)) z false (labelCode B a)))
36
+
37
+ def fourthTable (f : FoldedProof A) (g : FoldedProof A') (B : FaceArray A m n)
38
+ (C : FaceArray A' m n) (t : ScoreIndex m n → Bool) : ℝ :=
39
+ disagreement (f.answer (fun a => t (true,labelCode B a)))
40
+ (g.answer (fun a => t (true,labelCode C a)))
41
+
42
+ omit [Fintype A] in
43
+ lemma firstTable_source (f : FoldedProof A) (B : FaceArray A m n) (σ η : ℝ)
44
+ (c g : Point m n → ℝ) (l : Code m n → ℝ) :
45
+ firstTable f B (sourceTable σ η c g l)=firstFailure f B σ η c g l := rfl
46
+
47
+ omit [Fintype A] in
48
+ lemma secondTable_source (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ)
49
+ (c g : Point m n → ℝ) (l : Code m n → ℝ) :
50
+ secondTable f B C (sourceTable σ η c g l)=secondFailure f B C σ η c (g,l) := rfl
51
+
52
+ omit [Fintype A] in
53
+ lemma thirdTable_source (f : FoldedProof A) (B : FaceArray A m n) (σ η : ℝ)
54
+ (c g : Point m n → ℝ) (l : Code m n → ℝ) (z : Code m n) :
55
+ thirdTable f B z (sourceTable σ η c g l)=thirdFailure f B η (c+σ•g) l z := rfl
56
+
57
+ omit [Fintype A] [Fintype A'] in
58
+ lemma fourthTable_source (f : FoldedProof A) (g : FoldedProof A') (B : FaceArray A m n)
59
+ (C : FaceArray A' m n) (σ η : ℝ) (c h : Point m n → ℝ) (l : Code m n → ℝ) :
60
+ fourthTable f g B C (sourceTable σ η c h l)=comparisonFailure f g B C σ η c (h,l) := rfl
61
+
62
+ omit [Fintype A] in
63
+ lemma firstTable_integral (f : FoldedProof A) (B : FaceArray A m n) (σ η : ℝ) :
64
+ (∫ c, firstRejection f B σ η c ∂gauss (Point m n))=
65
+ ∫ x, firstTable f B (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) :=
66
+ table_integral_pack σ η (firstTable f B) (fun _ => disagreement_range _ _)
67
+
68
+ omit [Fintype A] in
69
+ lemma secondTable_integral (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) :
70
+ (∫ c, secondRejection f B C σ η c ∂gauss (Point m n))=
71
+ ∫ x, secondTable f B C (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) :=
72
+ table_integral_product σ η (secondTable f B C) (fun _ => disagreement_range _ _)
73
+
74
+ omit [Fintype A] in
75
+ lemma thirdTable_integral (f : FoldedProof A) (B : FaceArray A m n) (σ η : ℝ) :
76
+ (∫ c, thirdRejection f B σ η c ∂gauss (Point m n))=
77
+ 𝔼 z : Code m n, ∫ x, thirdTable f B z (thresholdTable (scoreFamily σ η) x)
78
+ ∂gaussianLaw (TestCoordinates m n) := by
79
+ unfold thirdRejection
80
+ simp only [Fintype.expect_eq_sum_div_card,integral_div]
81
+ simp_rw [← thirdTable_source]
82
+ rw [integral_finsetSum _ (fun z _ => sourceTest_outer_integrable σ η (thirdTable f B z)
83
+ (fun _ => disagreement_range _ _))]
84
+ congr 1
85
+ apply Finset.sum_congr rfl
86
+ intro z _
87
+ exact table_integral_pack σ η (thirdTable f B z) (fun _ => disagreement_range _ _)
88
+
89
+ omit [Fintype A] [Fintype A'] in
90
+ lemma fourthTable_integral (f : FoldedProof A) (g : FoldedProof A') (B : FaceArray A m n)
91
+ (C : FaceArray A' m n) (σ η : ℝ) :
92
+ (∫ c, comparisonRejection f g B C σ η c ∂gauss (Point m n))=
93
+ ∫ x, fourthTable f g B C (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) :=
94
+ table_integral_product σ η (fourthTable f g B C) (fun _ => disagreement_range _ _)
95
+
96
+ end MinUncut.FiniteGaussian
97
+
98
+ end
99
+ end
100
+
101
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/TemplateExpressions.lean ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Search.UniformQuantifier
3
+ import OAI.Computability.MinUncut.Estimates.UniformTransport
4
+ import OAI.Computability.MinUncut.Encoding.SignatureEncoding
5
+ import OAI.Computability.MinUncut.Search.TemplateArithmetic
6
+
7
+ namespace OAI
8
+
9
+ section
10
+ namespace MinUncut.SourceTemplate
11
+ open MinUncutGames.Foundations MinUncutGames.Foundations.Target
12
+ open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences
13
+ open MinUncutGames.Reduction.CloneGap
14
+ open MinUncut.Costed
15
+ open scoped BigOperators
16
+
17
+ def functionExpr {A : Type} (e : Encoding A) (b : ℕ) (f : A → AExpr) : AExpr :=
18
+ AExpr.sum (List.ofFn (fun i : Fin e.size => .mul (f (e.code.symm i)) (.const (b^i.val))))
19
+
20
+ lemma functionExpr_eval {A B : Type} (a : Encoding A) (b : Encoding B) (f : A → AExpr)
21
+ (g : A → B) (v : List ℕ) (h : ∀x,(f x).eval v=(b.code (g x)).val) :
22
+ (functionExpr a b.size f).eval v=((a.function b).code g).val := by
23
+ simp only [functionExpr,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn,AExpr.eval,h]
24
+ rfl
25
+
26
+ def positiveExpr (u : ℕ) : AExpr :=
27
+ functionExpr (Encoding.fin u) (2^3) (fun i => functionExpr slotEncoding 2 (fun s=>slotWord i.val s 1))
28
+ def sameExpr (u : ℕ) : AExpr :=
29
+ functionExpr (coordinateEncoding u) (2^(u*3)) (fun a =>
30
+ functionExpr (coordinateEncoding u) 2 (fun b=>.eq (slotWord a.1.val a.2 0) (slotWord b.1.val b.2 0)))
31
+ def signatureExpr (u : ℕ) : AExpr :=
32
+ .add (sameExpr u) (.mul (.const ((2^(u*3))^(u*3))) (positiveExpr u))
33
+
34
+ lemma positiveExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) :
35
+ (positiveExpr u).eval (inputTuple F c)=
36
+ ((((Encoding.fin u).function (slotEncoding.function Encoding.bool)).code (signature F c).positive)).val := by
37
+ unfold positiveExpr
38
+ apply functionExpr_eval (Encoding.fin u) (slotEncoding.function Encoding.bool)
39
+ intro i
40
+ apply functionExpr_eval slotEncoding Encoding.bool
41
+ intro s
42
+ rw [slotWord_positive,MinUncut.Outer.LocalTemplate.bool_code]
43
+ rfl
44
+
45
+ lemma sameExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) :
46
+ (sameExpr u).eval (inputTuple F c)=
47
+ ((((coordinateEncoding u).function ((coordinateEncoding u).function Encoding.bool)).code (signature F c).same)).val := by
48
+ unfold sameExpr
49
+ apply functionExpr_eval (coordinateEncoding u) ((coordinateEncoding u).function Encoding.bool)
50
+ intro a
51
+ apply functionExpr_eval (coordinateEncoding u) Encoding.bool
52
+ intro b
53
+ simp only [AExpr.eval,slotWord_name,signature,MinUncut.Outer.LocalTemplate.bool_code]
54
+ by_cases h : nameAt (clauseAt F (c a.1)) a.2=nameAt (clauseAt F (c b.1)) b.2
55
+ · simp only [h,ite_true,decide_true,Bool.toNat_true]
56
+ · have hh := Fin.val_ne_of_ne h
57
+ simp only [hh,ite_false,h,decide_false,Bool.toNat_false]
58
+
59
+ lemma signatureExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) :
60
+ (signatureExpr u).eval (inputTuple F c)=((signatureEncoding u).code (signature F c)).val := by
61
+ simp only [signatureExpr,AExpr.eval,positiveExpr_eval,sameExpr_eval]
62
+ rfl
63
+
64
+ def signatureLookup {u : ℕ} (f : Signature u → ℕ) : AExpr :=
65
+ (signatureExpr u).lookup (MinUncut.Outer.LocalTemplate.constantTable (signatureEncoding u) f)
66
+
67
+ lemma signatureLookup_eval (F : Formula) {u : ℕ} (c : ClauseContext F u)
68
+ (f : Signature u → ℕ) :
69
+ (signatureLookup f).eval (inputTuple F c)=f (signature F c) := by
70
+ apply MinUncut.Outer.LocalTemplate.constantTable_eval
71
+ exact signatureExpr_eval F c
72
+
73
+ def sampledExpr {u : ℕ} (s : SlotContext u) : AExpr :=
74
+ AExpr.sum (List.ofFn (fun i : Fin u=>.mul (slotWord i.val (s i) 0) ((AExpr.reg 1).pow i.val)))
75
+
76
+ lemma sampledExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) (s : SlotContext u) :
77
+ (sampledExpr s).eval (inputTuple F c)=
78
+ ((variableEncoding F u).code (sampledVariables F c s)).val := by
79
+ simp only [sampledExpr,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn,AExpr.eval,
80
+ AExpr.eval_pow,slotWord_name]
81
+ rfl
82
+
83
+ def addressExpr {u : ℕ} (s : SlotContext u) (f : Signature u → LocalKey u) : AExpr :=
84
+ let tag := signatureLookup (fun S=>keyTag (f S))
85
+ let table := signatureLookup (fun S=>keyTable (f S))
86
+ let leftSize := .mul ((AExpr.reg 1).pow u) (.const (2^(2^u)))
87
+ .cond (.eq tag (.const 0))
88
+ (.cond (.eq tag (.const 1))
89
+ (.add leftSize (.mul ((AExpr.reg 2).pow u) (.const (2^(8^u)))))
90
+ (.add leftSize (.add table (.mul (.const (2^(8^u))) (.reg 0)))))
91
+ (.add table (.mul (.const (2^(2^u))) (sampledExpr s)))
92
+
93
+ lemma addressExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u)
94
+ (s : SlotContext u) (f : Signature u → LocalKey u) :
95
+ (addressExpr s f).eval (inputTuple F c)=
96
+ (keyAddress F c (sampledVariables F c s) (f (signature F c))).val := by
97
+ rw [keyAddress_number]
98
+ simp only [addressExpr,AExpr.eval,signatureLookup_eval,sampledExpr_eval,AExpr.eval_pow]
99
+ by_cases h0 : keyTag (f (signature F c))=0
100
+ · simp only [h0,ite_true,Nat.one_ne_zero,ite_false,keyNumber]
101
+ · by_cases h1 : keyTag (f (signature F c))=1 <;>
102
+ simp only [h0,h1,ite_true,ite_false,Nat.one_ne_zero,keyNumber,inputTuple,
103
+ Complexity.formulaWords,List.cons_append,List.nil_append,List.drop_succ_cons,
104
+ List.drop_zero,List.headI_cons]
105
+
106
+ def equationExpressions {u D : ℕ} (s : SlotContext u)
107
+ (t : SourceTape.TestTape (I u) (J u) D) : List AExpr :=
108
+ [addressExpr s (fun S=>(S.equation s t).first),
109
+ addressExpr s (fun S=>(S.equation s t).second),
110
+ addressExpr s (fun S=>(S.equation s t).third),
111
+ signatureLookup (fun S=>(S.equation s t).rhs.toNat)]
112
+
113
+ lemma equationExpressions_eval (F : Formula) {u D : ℕ} (c : ClauseContext F u)
114
+ (s : SlotContext u) (t : SourceTape.TestTape (I u) (J u) D) :
115
+ (equationExpressions s t).map (fun e=>e.eval (inputTuple F c))=
116
+ MinUncutGames.Reduction.SourceEncoding.equationWords (sourceEquation F u D ((c,s),t)) := by
117
+ rw [←signature_equation]
118
+ simp only [equationExpressions,List.map_cons,List.map_nil,addressExpr_eval,signatureLookup_eval]
119
+ unfold mapEquation MinUncutGames.Reduction.SourceEncoding.equationWords
120
+ congr 3
121
+ cases ((signature F c).equation s t).rhs <;> rfl
122
+
123
+ end MinUncut.SourceTemplate
124
+
125
+ end
126
+ section
127
+ noncomputable section
128
+ namespace MinUncut.Preprocess.Syntax
129
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
130
+ open MinUncut.FiniteProof MinUncut.Costed MinUncut.CodeEffective Turing.ToPartrec UEncoding
131
+ variable {P : Type} [Primcodable P] {A B : P → Type} {c : UEncoding P A}
132
+ lemma O.ofEq {f g : ∀p,A p → AExpr} (hf : O c f) (h : ∀p x,f p x=g p x) : O c g :=
133
+ Out.ofEq hf (fun p x=>congrArg (fun a:AExpr=>a.program.code) (h p x))
134
+
135
+ def eqCode (a b : Code) : Code := branch (bin PolyProgram.add.code
136
+ (bin PolyProgram.sub.code a b) (bin PolyProgram.sub.code b a)) (constCode 1) (constCode 0)
137
+ lemma p_eqCode : Primrec₂ eqCode := p_branch.comp
138
+ (((p_bin _).comp ((p_bin _).comp Primrec.fst Primrec.snd)
139
+ ((p_bin _).comp Primrec.snd Primrec.fst)).pair
140
+ ((Primrec.const (constCode 1)).pair (Primrec.const (constCode 0))))
141
+ def lookupCode (a : Code) (xs : List (ℕ × ℕ)) : Code := xs.foldr
142
+ (fun ix b=>branch (eqCode a (constCode ix.1)) b (constCode ix.2)) (constCode 0)
143
+ lemma p_lookupCode : Primrec₂ lookupCode := by
144
+ exact Primrec.list_foldr Primrec.snd (Primrec.const (constCode 0))
145
+ (p_branch.comp
146
+ ((p_eqCode.comp (Primrec.fst.comp Primrec.fst)
147
+ (p_constCode.comp (Primrec.fst.comp (Primrec.fst.comp Primrec.snd)))).pair
148
+ (Primrec.snd.comp Primrec.snd |>.pair
149
+ (p_constCode.comp (Primrec.snd.comp (Primrec.fst.comp Primrec.snd)))))).to₂
150
+ lemma lookupCode_eq (a : AExpr) (xs : List (ℕ × ℕ)) :
151
+ lookupCode a.program.code xs=(a.lookup xs).program.code := by
152
+ induction xs with
153
+ | nil => rfl
154
+ | cons ix xs ih =>
155
+ simp only [lookupCode,List.foldr_cons] at *
156
+ rw [ih]
157
+ rw [AExpr.lookup,cond_code,eq_code]
158
+ rfl
159
+ lemma O.lookup {a : ∀p,A p → AExpr} {xs : ∀p,A p → List (ℕ × ℕ)}
160
+ (ha : O c a) (hx : c.Out xs) : O c (fun p x=>(a p x).lookup (xs p x)) :=
161
+ (ha.map₂ hx p_lookupCode.to_comp).ofEq (fun p x=>lookupCode_eq (a p x) (xs p x))
162
+ lemma O.sum_enum {b : UEncoding P B} {f : ∀p,A p × B p → AExpr}
163
+ (hf : O (c.prod b) f) : O c (fun p x=>AExpr.sum ((b.enc p).enumerate.map (fun y=>f p (x,y)))) := by
164
+ apply O.sum
165
+ apply (out_list hf).ofEq
166
+ intro p x
167
+ simp only [List.map_map,Function.comp_def]
168
+ lemma O.sum_fin {n : P → ℕ} (hn : Computable n) {f : ∀p,A p × Fin (n p) → AExpr}
169
+ (hf : O (c.prod (fin n hn)) f) : O c (fun p x=>AExpr.sum (List.ofFn (fun i=>f p (x,i)))) := by
170
+ apply hf.sum_enum.ofEq
171
+ intro p x
172
+ simp only [fin,Encoding.fin,Encoding.enumerate,List.map_ofFn,Function.comp_def,Equiv.refl_symm]
173
+ rfl
174
+ lemma out_constantTable {b : UEncoding P B} {f : ∀p,A p × B p → ℕ}
175
+ (hf : (c.prod b).Out f) : c.Out (fun p x=>MinUncut.Outer.LocalTemplate.constantTable (b.enc p) (fun y=>f p (x,y))) :=
176
+ out_list ((out_code b).second.pair hf)
177
+ lemma O.functionExpr {b : UEncoding P B} {base : P → ℕ} (hb : Computable base)
178
+ {f : ∀p,A p × B p → AExpr} (hf : O (c.prod b) f) :
179
+ O c (fun p x=>MinUncut.SourceTemplate.functionExpr (b.enc p) (base p) (fun y=>f p (x,y))) := by
180
+ have hpow : (c.prod b).Out (fun p x=>base p ^ ((b.enc p).code x.2).val) :=
181
+ (out_const _ hb).map₂ (out_code b).second (ca_pow Computable.fst Computable.snd)
182
+ apply (hf.mul (O.const hpow)).sum_enum.ofEq
183
+ intro p x
184
+ simp only [MinUncut.SourceTemplate.functionExpr,Encoding.enumerate,List.map_ofFn,Function.comp_def,Equiv.apply_symm_apply]
185
+ end MinUncut.Preprocess.Syntax
186
+
187
+ end
188
+ end
189
+ section
190
+ namespace MinUncut.Preprocess.Source
191
+ open MinUncutGames.Foundations MinUncutGames.Foundations.Target
192
+ open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences
193
+ open MinUncut.SourceTemplate UEncoding
194
+
195
+ def positions : UEncoding ℕ Fin := UEncoding.fin id Computable.id
196
+ def slots : UEncoding ℕ (fun _=>Slot) := fixed slotEncoding
197
+ def answers : UEncoding ℕ (fun _=>ClauseAnswer) := fixed clauseAnswerEncoding
198
+ def lefts : UEncoding ℕ I := positions.function bool
199
+ def rights : UEncoding ℕ J := positions.function answers
200
+ def coordinates : UEncoding ℕ (fun u=>Fin u × Slot) := positions.prod slots
201
+ def polarities : UEncoding ℕ (fun u=>Fin u → Slot → Bool) := positions.function (slots.function bool)
202
+ def equalities : UEncoding ℕ (fun u=>(Fin u × Slot) → (Fin u × Slot) → Bool) :=
203
+ coordinates.function (coordinates.function bool)
204
+ def signatures : UEncoding ℕ Signature := (polarities.prod equalities).ofEquiv signatureEquiv
205
+
206
+ lemma signatures_encoding (u : ℕ) : signatures.enc u=signatureEncoding u := rfl
207
+ lemma map_positive : signatures.Map polarities (fun _ s=>s.positive) := by
208
+ change ((polarities.prod equalities).ofEquiv signatureEquiv).Map polarities (fun u s=>(signatureEquiv u s).1)
209
+ exact map_comp (map_to (polarities.prod equalities) signatureEquiv) (map_fst polarities equalities)
210
+ lemma map_same : signatures.Map equalities (fun _ s=>s.same) := by
211
+ change ((polarities.prod equalities).ofEquiv signatureEquiv).Map equalities (fun u s=>(signatureEquiv u s).2)
212
+ exact map_comp (map_to (polarities.prod equalities) signatureEquiv) (map_snd polarities equalities)
213
+
214
+ variable {Γ : ℕ → Type} {g : UEncoding ℕ Γ}
215
+ lemma map_satisfies {s : ∀u,Γ u → Signature u} {j : ∀u,Γ u → J u} {t : ∀u,Γ u → Fin u}
216
+ (hs : g.Map signatures s) (hj : g.Map rights j) (ht : g.Map positions t) :
217
+ g.Map bool (fun u x=>(s u x).satisfies (j u x) (t u x)) := by
218
+ exact map_binary (slotEncoding.function Encoding.bool) clauseAnswerEncoding Encoding.bool
219
+ (fun p a=>(literalValue (p .first) a.first || literalValue (p .second) a.second) ||
220
+ literalValue (p .third) a.third)
221
+ (map_apply (map_comp hs map_positive) ht) (map_apply hj ht)
222
+
223
+ lemma map_same_at {s : ∀u,Γ u → Signature u} {a b : ∀u,Γ u → Fin u × Slot}
224
+ (hs : g.Map signatures s) (ha : g.Map coordinates a) (hb : g.Map coordinates b) :
225
+ g.Map bool (fun u x=>(s u x).same (a u x) (b u x)) :=
226
+ map_apply (map_apply (map_comp hs map_same) ha) hb
227
+ lemma map_answer_at {j : ∀u,Γ u → J u} {a : ∀u,Γ u → Fin u × Slot}
228
+ (hj : g.Map rights j) (ha : g.Map coordinates a) :
229
+ g.Map bool (fun u x=>answerAt (j u x (a u x).1) (a u x).2) :=
230
+ map_binary clauseAnswerEncoding slotEncoding Encoding.bool answerAt
231
+ (map_apply hj (map_comp ha (map_fst _ _))) (map_comp ha (map_snd _ _))
232
+
233
+ lemma map_consistent {s : ∀u,Γ u → Signature u} {j : ∀u,Γ u → J u}
234
+ {a b : ∀u,Γ u → Fin u × Slot}
235
+ (hs : g.Map signatures s) (hj : g.Map rights j)
236
+ (ha : g.Map coordinates a) (hb : g.Map coordinates b) :
237
+ g.Map bool (fun u x=>decide ((s u x).same (a u x) (b u x)=true →
238
+ answerAt (j u x (a u x).1) (a u x).2=answerAt (j u x (b u x).1) (b u x).2)) := by
239
+ apply (map_or (map_not (map_same_at hs ha hb))
240
+ (map_bool_eq (map_answer_at hj ha) (map_answer_at hj hb))).ofEq
241
+ intro u x
242
+ by_cases h:(s u x).same (a u x) (b u x)=true <;> simp [h]
243
+
244
+ lemma map_valid : (signatures.prod rights).Map bool (fun _ x=>x.1.valid x.2) := by
245
+ classical
246
+ have hs : ((signatures.prod rights).prod positions).Map bool
247
+ (fun u x=>x.1.1.satisfies x.1.2 x.2) :=
248
+ map_satisfies (map_fst signatures rights).first (map_snd signatures rights).first (map_snd _ _)
249
+ have hc : (((signatures.prod rights).prod coordinates).prod coordinates).Map bool
250
+ (fun u x=>decide (x.1.1.1.same x.1.2 x.2=true →
251
+ answerAt (x.1.1.2 x.1.2.1) x.1.2.2=answerAt (x.1.1.2 x.2.1) x.2.2)) :=
252
+ map_consistent (map_fst signatures rights).first.first (map_snd signatures rights).first.first
253
+ (map_snd (signatures.prod rights) coordinates).first (map_snd _ _)
254
+ apply (map_and (map_forall hs) (map_forall (map_forall hc))).ofEq
255
+ intro u x
256
+ simp only [Signature.valid,Bool.decide_and,decide_eq_true_eq]
257
+ congr 1
258
+ apply decide_eq_decide.mpr
259
+ simp only [Prod.forall]
260
+ constructor
261
+ · intro h t t' s s' he
262
+ exact h t s t' s' he
263
+ · intro h t s t' s' he
264
+ exact h t t' s s' he
265
+
266
+ end MinUncut.Preprocess.Source
267
+
268
+ end
269
+ section
270
+ namespace MinUncut.Preprocess.Source
271
+ open MinUncutGames.Foundations MinUncutGames.Foundations.Target
272
+ open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences
273
+ open MinUncut.SourceTemplate UEncoding
274
+
275
+ def slotContexts : UEncoding ℕ SlotContext := positions.function slots
276
+
277
+ variable {Γ : ℕ → Type} {g : UEncoding ℕ Γ}
278
+ lemma map_slot {s : ∀u,Γ u → Signature u} {r : ∀u,Γ u → SlotContext u} {t : ∀u,Γ u → Fin u}
279
+ (hs : g.Map signatures s) (hr : g.Map slotContexts r) (ht : g.Map positions t) :
280
+ g.Map slots (fun u x=>(s u x).slot (r u x) (t u x)) := by
281
+ exact map_binary Encoding.bool Encoding.bool slotEncoding
282
+ (fun b c=>if b then .first else if c then .second else .third)
283
+ (map_same_at hs (map_pair ht (map_const (Computable.const 0))) (map_pair ht (map_apply hr ht)))
284
+ (map_same_at hs (map_pair ht (map_const (Computable.const 1))) (map_pair ht (map_apply hr ht)))
285
+
286
+ lemma map_project {s : ∀u,Γ u → Signature u} {r : ∀u,Γ u → SlotContext u} {j : ∀u,Γ u → J u}
287
+ (hs : g.Map signatures s) (hr : g.Map slotContexts r) (hj : g.Map rights j) :
288
+ g.Map lefts (fun u x=>(s u x).project (r u x) (j u x)) := by
289
+ exact map_lambda (map_binary clauseAnswerEncoding slotEncoding Encoding.bool answerAt
290
+ (map_apply hj.first (map_snd g positions))
291
+ (map_slot hs.first hr.first (map_snd g positions)))
292
+
293
+ lemma map_anchor (a : UEncoding ℕ Γ) : a.Map lefts (fun u _=>leftAnchor u) :=
294
+ map_lambda (map_false (a.prod positions))
295
+
296
+ end MinUncut.Preprocess.Source
297
+
298
+ namespace MinUncut.Preprocess.UEncoding
299
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
300
+ open MinUncutGames.Foundations.Hastad
301
+ variable {P : Type} [Primcodable P] {A Γ : P → Type}
302
+ lemma map_xor {g : UEncoding P Γ} {f h : ∀p,Γ p → Bool}
303
+ (hf : g.Map bool f) (hh : g.Map bool h) : g.Map bool (fun p x=>f p x ^^ h p x) :=
304
+ map_binary Encoding.bool Encoding.bool Encoding.bool Bool.xor hf hh
305
+
306
+ lemma map_representative {g : UEncoding P Γ} {a : UEncoding P A}
307
+ {f : ∀p,Γ p → A p → Bool} {i : ∀p,Γ p → A p}
308
+ (hf : g.Map (a.function bool) f) (hi : g.Map a i) :
309
+ g.Map (a.function bool) (fun p x=>representative (i p x) (f p x)) := by
310
+ apply (map_lambda (map_xor (map_apply hf.first (map_snd g a)) (map_apply hf hi).first)).ofEq
311
+ intro p x
312
+ funext y
313
+ change (f p x y ^^ f p x (i p x))=(if f p x (i p x) then cubeFlip (f p x) else f p x) y
314
+ cases f p x (i p x) <;> simp [cubeFlip]
315
+ end MinUncut.Preprocess.UEncoding
316
+
317
+ end
318
+ section
319
+ namespace MinUncut.SourceTemplate
320
+ open MinUncutGames.Foundations MinUncutGames.Foundations.Target
321
+ open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences
322
+ open MinUncutGames.Reduction.CloneGap
323
+
324
+ def paddedRep {u : ℕ} (valid : J u → Bool) (j₀ : J u) (g : Cube (J u)) : Cube (J u) :=
325
+ fun j=>if valid j then representative j₀ g j else false
326
+
327
+ lemma extend_representative {u : ℕ} (valid : J u → Bool)
328
+ (j₀ : {j : J u // valid j=true}) (g : Cube (J u)) :
329
+ extendRestricted valid (representative j₀ (restrictQuery valid g))=paddedRep valid j₀ g := by
330
+ funext j
331
+ unfold extendRestricted paddedRep
332
+ by_cases h:valid j=true
333
+ · simp only [h,↓reduceDIte,ite_true]
334
+ cases h₀:g j₀ <;> simp [representative,restrictQuery,cubeFlip,h₀]
335
+ · simp [h]
336
+
337
+ lemma findValid_map {X : Type} (valid : X → Bool) (xs : List X) :
338
+ (findValid valid xs).map Subtype.val=xs.find? valid := by
339
+ induction xs with
340
+ | nil => rfl
341
+ | cons x xs ih =>
342
+ by_cases h:valid x=true <;> simp [findValid,h,ih]
343
+
344
+ def rawLocal {u : ℕ} (valid : J u → Bool) (π : J u → I u)
345
+ (f : Cube (I u)) (g μ : Cube (J u)) : Equation (LocalKey u) :=
346
+ ((jEncoding u).enumerate.find? valid).elim
347
+ ⟨.inl (representative (leftAnchor u) f),.inr (.inr ()),.inr (.inr ()),f (leftAnchor u)⟩
348
+ (fun j₀=>⟨.inl (representative (leftAnchor u) f),
349
+ .inr (.inl (paddedRep valid j₀ g)),
350
+ .inr (.inl (paddedRep valid j₀ (thirdQuery π f g μ))),
351
+ f (leftAnchor u) ^^ f (π j₀) ^^ μ j₀⟩)
352
+
353
+ lemma rawLocal_eq {u D : ℕ} (valid : J u → Bool) (π : J u → I u)
354
+ (t : SourceTape.TestTape (I u) (J u) D) :
355
+ rawLocal valid π t.1 t.2.2 (MinUncutGames.Reduction.FiniteNoise.realizedNoise t.2.1)=
356
+ localEquation valid π t := by
357
+ rw [rawLocal,←findValid_map,←firstValid]
358
+ unfold localEquation
359
+ cases hh:firstValid (jEncoding u) valid with
360
+ | none => rfl
361
+ | some j₀ =>
362
+ dsimp only [Option.map_some,Option.elim_some,mapEquation,FoldedEquation.conditionedEquation,
363
+ FoldedEquation.equation,foldedLocal,canonicalInput]
364
+ rw [extend_representative]
365
+ have he : thirdQuery (fun j:{j : J u // valid j=true}=>π j.val) t.1
366
+ (restrictQuery valid t.2.2)
367
+ (restrictQuery valid (MinUncutGames.Reduction.FiniteNoise.realizedNoise t.2.1))=
368
+ restrictQuery valid (thirdQuery π t.1 t.2.2
369
+ (MinUncutGames.Reduction.FiniteNoise.realizedNoise t.2.1)) := rfl
370
+ rw [he,extend_representative]
371
+ rfl
372
+ end MinUncut.SourceTemplate
373
+
374
+ end
375
+
376
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformAlgebra.lean ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.UniformTransport
3
+ import OAI.Computability.MinUncut.Estimates.UniformRestrict
4
+ import OAI.Computability.MinUncut.Encoding.QuestionEncoding
5
+
6
+ namespace OAI
7
+
8
+ section
9
+ namespace MinUncut.Preprocess
10
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
11
+ open scoped BigOperators
12
+ variable {P X : Type} [Primcodable P] [Primcodable X] [AddCommMonoid X]
13
+
14
+ lemma c_rangeSum {f : P → ℕ → X} (hf : Computable₂ f)
15
+ (hadd : Computable₂ (fun x y : X=>x+y)) :
16
+ Computable₂ (fun p n=>((List.range n).map (f p)).sum) := by
17
+ have hh := Computable.nat_rec (α:=P × ℕ) (σ:=X) Computable.snd
18
+ (Computable.const 0)
19
+ (hadd.comp (Computable.snd.comp Computable.snd)
20
+ (hf.comp (Computable.fst.comp Computable.fst) (Computable.fst.comp Computable.snd))).to₂
21
+ exact hh.of_eq (by
22
+ intro p
23
+ induction p.2 with
24
+ | zero => rfl
25
+ | succ n ih => simp only [List.range_succ,List.map_append,List.map_singleton,List.sum_append,
26
+ List.sum_singleton,ih])
27
+
28
+ namespace UEncoding
29
+ variable {A B Γ : P → Type}
30
+ omit [AddCommMonoid X] in
31
+ lemma Out.toFixed {a : UEncoding P A} {b : Encoding X} [Finite X]
32
+ {f : ∀p,A p → X} (hf : a.Out f) : a.Map (fixed b) f := by
33
+ obtain ⟨f',hr,he⟩:=hf
34
+ exact ⟨_,(Primrec.dom_finite (fun x=>(b.code x).val)).to_comp.comp hr,
35
+ by intro p x; dsimp only; rw [he]; rfl⟩
36
+
37
+ lemma out_sum {g : UEncoding P Γ} {a : UEncoding P A}
38
+ [∀p,Fintype (A p)] {f : ∀p,Γ p × A p → X} (hf : (g.prod a).Out f)
39
+ (hadd : Computable₂ (fun x y : X=>x+y)) :
40
+ g.Out (fun p s=>∑x,f p (s,x)) := by
41
+ obtain ⟨f',hf',hf⟩:=hf
42
+ let raw : (P × ℕ) → ℕ → X := fun q i=>f' (q.1,q.2*(a.enc q.1).size+i)
43
+ have hr : Computable₂ raw := by
44
+ unfold raw
45
+ exact hf'.comp ((Computable.fst.comp Computable.fst).pair
46
+ (ca_add (ca_mul (Computable.snd.comp Computable.fst)
47
+ (a.computableSize.comp (Computable.fst.comp Computable.fst))) Computable.snd))
48
+ refine ⟨fun q=>((List.range (a.enc q.1).size).map (raw q)).sum,
49
+ (c_rangeSum hr hadd).comp Computable.id (a.computableSize.comp Computable.fst),?_⟩
50
+ intro p s
51
+ dsimp only
52
+ have he : ((a.enc p).enumerate.map (fun x=>f p (s,x))).sum=∑x,f p (s,x) := by
53
+ classical
54
+ have ht : (a.enc p).enumerate.toFinset=Finset.univ := by ext x; simp [(a.enc p).mem_enumerate x]
55
+ rw [← List.sum_toFinset _ (a.enc p).nodup_enumerate,ht]
56
+ rw [←he,Encoding.enumerate,List.ofFn_eq_map,List.map_map]
57
+ rw [←finRange_values ((a.enc p).size),List.map_map]
58
+ apply congrArg List.sum
59
+ apply List.map_congr_left
60
+ intro i hi
61
+ have hh:=hf p (s,(a.enc p).code.symm i)
62
+ change f' (p,(((g.enc p).prod (a.enc p)).code (s,(a.enc p).code.symm i)).val)=_ at hh
63
+ rw [prod_code,Equiv.apply_symm_apply] at hh
64
+ exact hh
65
+
66
+ instance primcodableF₂ : Primcodable MinUncut.Inner.F₂ :=
67
+ Primcodable.ofEquiv (Fin 2) MinUncut.Outer.fieldEncoding.code
68
+
69
+ abbrev field (P : Type) [Primcodable P] := fixed (P:=P) MinUncut.Outer.fieldEncoding
70
+
71
+ lemma out_field (a : UEncoding P A) {f : ∀p,A p → MinUncut.Inner.F₂}
72
+ (hf : a.Map (field P) f) : a.Out f := hf.out 0
73
+ lemma map_field_add {a : UEncoding P A} {f g : ∀p,A p → MinUncut.Inner.F₂}
74
+ (hf : a.Map (field P) f) (hg : a.Map (field P) g) :
75
+ a.Map (field P) (fun p x=>f p x+g p x) :=
76
+ ((out_field a hf).map₂ (out_field a hg) (Primrec.dom_finite _).to_comp).toFixed
77
+ lemma map_field_mul {a : UEncoding P A} {f g : ∀p,A p → MinUncut.Inner.F₂}
78
+ (hf : a.Map (field P) f) (hg : a.Map (field P) g) :
79
+ a.Map (field P) (fun p x=>f p x*g p x) :=
80
+ ((out_field a hf).map₂ (out_field a hg) (Primrec.dom_finite _).to_comp).toFixed
81
+ lemma map_field_sum {g : UEncoding P Γ} {a : UEncoding P A} [∀p,Fintype (A p)]
82
+ {f : ∀p,Γ p × A p → MinUncut.Inner.F₂} (hf : (g.prod a).Map (field P) f) :
83
+ g.Map (field P) (fun p s=>∑x,f p (s,x)) :=
84
+ (out_sum (out_field _ hf) (Primrec.dom_finite _).to_comp).toFixed
85
+ end UEncoding
86
+ end MinUncut.Preprocess
87
+
88
+ end
89
+
90
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformBoolean.lean ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Encoding.UniformEncoding
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ namespace MinUncut.Preprocess
8
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
9
+ namespace UEncoding
10
+ variable {P : Type} [Primcodable P] {A B C Γ : P → Type}
11
+
12
+ def fixed {X : Type} (e : Encoding X) : UEncoding P (fun _=>X) :=
13
+ ⟨fun _=>e,Computable.const e.size⟩
14
+ def bool : UEncoding P (fun _=>Bool) := fixed Encoding.bool
15
+ def fin (n : P → ℕ) (hn : Computable n) : UEncoding P (fun p=>Fin (n p)) :=
16
+ ⟨fun p=>Encoding.fin (n p),hn⟩
17
+
18
+ lemma map_const {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,B p}
19
+ (hf : Computable (fun p=>((b.enc p).code (f p)).val)) :
20
+ a.Map b (fun p _=>f p) :=
21
+ ⟨_,hf.comp Computable.fst,by intros; rfl⟩
22
+
23
+ lemma bool_code (x : Bool) : (Encoding.bool.code x).val=x.toNat := by
24
+ cases x <;> rfl
25
+
26
+ lemma map_bool_eq {a : UEncoding P A} {b : UEncoding P B}
27
+ {f g : ∀p,A p → B p} [∀p,DecidableEq (B p)]
28
+ (hf : a.Map b f) (hg : a.Map b g) :
29
+ a.Map bool (fun p x=>decide (f p x=g p x)) := by
30
+ obtain ⟨f',hf',hf⟩:=hf
31
+ obtain ⟨g',hg',hg⟩:=hg
32
+ refine ⟨fun q=>(decide (f' q=g' q)).toNat,?_,?_⟩
33
+ · exact (Primrec.dom_bool Bool.toNat).to_comp.comp
34
+ (Primrec.eq.decide.to_comp.comp hf' hg')
35
+ · intro p x
36
+ dsimp only
37
+ rw [hf,hg]
38
+ change _=(Encoding.bool.code _).val
39
+ rw [bool_code]
40
+ congr 2
41
+ exact propext (Fin.val_inj.trans (b.enc p).code.injective.eq_iff)
42
+
43
+ lemma map_cond {a : UEncoding P A} {b : UEncoding P B}
44
+ {c : ∀p,A p → Bool} {f g : ∀p,A p → B p}
45
+ (hc : a.Map bool c) (hf : a.Map b f) (hg : a.Map b g) :
46
+ a.Map b (fun p x=>if c p x then f p x else g p x) := by
47
+ obtain ⟨c',hc',hc⟩:=hc
48
+ obtain ⟨f',hf',hf⟩:=hf
49
+ obtain ⟨g',hg',hg⟩:=hg
50
+ refine ⟨fun q=>if c' q=1 then f' q else g' q,?_,?_⟩
51
+ · exact (Computable.cond (Primrec.eq.decide.to_comp.comp hc' (Computable.const 1)) hf' hg').of_eq (by intro q; simp)
52
+ · intro p x
53
+ dsimp only
54
+ rw [hc,hf,hg]
55
+ change (if (Encoding.bool.code (c p x)).val=1 then _ else _)=_
56
+ rw [bool_code]
57
+ cases h:c p x <;> simp
58
+
59
+ lemma map_fixed {X Y : Type} (a : Encoding X) (b : Encoding Y) (f : X → Y) :
60
+ (fixed (P:=P) a).Map (fixed b) (fun _ x=>f x) := by
61
+ let table := List.ofFn (fun i : Fin a.size=>(b.code (f (a.code.symm i))).val)
62
+ refine ⟨fun q=>(table[q.2]?).getD 0,?_,?_⟩
63
+ · exact Primrec.option_getD_default.to_comp.comp
64
+ ((Primrec.list_getElem?₁ table).to_comp.comp Computable.snd)
65
+ · intro p x
66
+ dsimp only
67
+ change (table[(a.code x).val]?).getD 0=(b.code (f x)).val
68
+ simp [table,(a.code x).isLt]
69
+
70
+ lemma map_fixed_apply {X Y : Type} {a : UEncoding P A} (b : Encoding X) (c : Encoding Y)
71
+ (op : X → Y) {f : ∀p,A p → X} (hf : a.Map (fixed b) f) :
72
+ a.Map (fixed c) (fun p x=>op (f p x)) :=
73
+ map_comp hf (map_fixed b c op)
74
+
75
+ lemma map_binary {X Y Z : Type} {a : UEncoding P A}
76
+ (b : Encoding X) (c : Encoding Y) (d : Encoding Z) (op : X → Y → Z)
77
+ {f : ∀p,A p → X} {g : ∀p,A p → Y}
78
+ (hf : a.Map (fixed b) f) (hg : a.Map (fixed c) g) :
79
+ a.Map (fixed d) (fun p x=>op (f p x) (g p x)) :=
80
+ map_comp (map_pair hf hg) (map_fixed (b.prod c) d (fun x=>op x.1 x.2))
81
+
82
+ lemma map_not {a : UEncoding P A} {f : ∀p,A p → Bool} (hf : a.Map bool f) :
83
+ a.Map bool (fun p x=>!(f p x)) :=
84
+ map_fixed_apply Encoding.bool Encoding.bool Bool.not hf
85
+ lemma map_and {a : UEncoding P A} {f g : ∀p,A p → Bool}
86
+ (hf : a.Map bool f) (hg : a.Map bool g) : a.Map bool (fun p x=>f p x && g p x) :=
87
+ map_binary Encoding.bool Encoding.bool Encoding.bool Bool.and hf hg
88
+ lemma map_or {a : UEncoding P A} {f g : ∀p,A p → Bool}
89
+ (hf : a.Map bool f) (hg : a.Map bool g) : a.Map bool (fun p x=>f p x || g p x) :=
90
+ map_binary Encoding.bool Encoding.bool Encoding.bool Bool.or hf hg
91
+
92
+ end UEncoding
93
+ end MinUncut.Preprocess
94
+
95
+ end
96
+
97
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformEquation.lean ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Search.UniformFind
3
+ import OAI.Computability.MinUncut.Estimates.UniformAlgebra
4
+ import OAI.Computability.MinUncut.Analysis.UniformCube
5
+
6
+ namespace OAI
7
+
8
+ namespace MinUncut.Preprocess.Source
9
+ open MinUncutGames.Foundations MinUncutGames.Foundations.Target
10
+ open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences
11
+ open MinUncutGames.Reduction.CloneGap
12
+ open MinUncut.SourceTemplate UEncoding
13
+
14
+ abbrev Par := ℕ × ℕ
15
+ abbrev up {A : ℕ → Type} (a : UEncoding ℕ A) : UEncoding Par (fun p=>A p.1) := a.pullback Prod.fst Computable.fst
16
+
17
+ def ls : UEncoding Par (fun p=>I p.1) := up lefts
18
+ def rs : UEncoding Par (fun p=>J p.1) := up rights
19
+ def fc := ls.function bool
20
+ def gc := rs.function bool
21
+ def keys : UEncoding Par (fun p=>LocalKey p.1) := fc.sum (gc.sum (fixed Encoding.unit))
22
+
23
+ variable {Γ : Par → Type} {e : UEncoding Par Γ}
24
+ lemma map_rawLocal {v : ∀p,Γ p → J p.1 → Bool} {π : ∀p,Γ p → J p.1 → I p.1}
25
+ {f : ∀p,Γ p → Cube (I p.1)} {g μ : ∀p,Γ p → Cube (J p.1)}
26
+ (hv : e.Map gc v) (hπ : e.Map (rs.function ls) π)
27
+ (hf : e.Map fc f) (hg : e.Map gc g) (hμ : e.Map gc μ) :
28
+ e.Map keys.equation (fun p x=>rawLocal (v p x) (π p x) (f p x) (g p x) (μ p x)) := by
29
+ have ha : e.Map ls (fun p _=>leftAnchor p.1) :=
30
+ map_lambda (map_false (e.prod (up positions)))
31
+ have hfirst := map_comp (map_representative hf ha) (map_inl fc (gc.sum (fixed Encoding.unit)))
32
+ have hdummy : e.Map keys (fun _ _=>Sum.inr (Sum.inr ())) :=
33
+ map_comp (map_comp (map_const (Computable.const 0)) (map_inr gc (fixed Encoding.unit)))
34
+ (map_inr fc (gc.sum (fixed Encoding.unit)))
35
+ have hnone : e.Map keys.equation (fun p x=>
36
+ ⟨.inl (representative (leftAnchor p.1) (f p x)),.inr (.inr ()),.inr (.inr ()),f p x (leftAnchor p.1)⟩) :=
37
+ map_equation hfirst hdummy hdummy (map_apply hf ha)
38
+ have hright (h : e.Map gc g) : (e.prod rs).Map keys
39
+ (fun p x=>.inr (.inl (paddedRep (v p x.1) x.2 (g p x.1)))) :=
40
+ map_comp (map_comp (map_padded hv.first h.first (map_snd e rs))
41
+ (map_inl gc (fixed Encoding.unit))) (map_inr fc (gc.sum (fixed Encoding.unit)))
42
+ have hthird := map_thirdQuery hπ hf hg hμ
43
+ have hsome : (e.prod rs).Map keys.equation (fun p x=>
44
+ ⟨.inl (representative (leftAnchor p.1) (f p x.1)),
45
+ .inr (.inl (paddedRep (v p x.1) x.2 (g p x.1))),
46
+ .inr (.inl (paddedRep (v p x.1) x.2 (thirdQuery (π p x.1) (f p x.1) (g p x.1) (μ p x.1)))),
47
+ f p x.1 (leftAnchor p.1) ^^ f p x.1 (π p x.1 x.2) ^^ μ p x.1 x.2⟩) := by
48
+ exact map_equation hfirst.first (hright hg)
49
+ (map_comp (map_comp (map_padded hv.first hthird.first (map_snd e rs))
50
+ (map_inl gc (fixed Encoding.unit))) (map_inr fc (gc.sum (fixed Encoding.unit))))
51
+ (map_xor (map_xor (map_apply hf ha).first
52
+ (map_apply hf.first (map_apply hπ.first (map_snd e rs))))
53
+ (map_apply hμ.first (map_snd e rs)))
54
+ apply (map_comp (map_pair (map_id e) (map_find_apply hv)) (map_option_elim hnone hsome)).ofEq
55
+ intro p x
56
+ rfl
57
+
58
+ def ds : UEncoding Par (fun p=>Fin p.2) := fin Prod.snd Computable.snd
59
+ def tapes : UEncoding Par (fun p=>SourceTape.TestTape (I p.1) (J p.1) p.2) :=
60
+ fc.prod ((rs.function ds).prod gc)
61
+ def sigs := up signatures
62
+ def sls := up slotContexts
63
+ def context := (sigs.prod sls).prod tapes
64
+
65
+ lemma map_context_signature : context.Map sigs (fun _ x=>x.1.1) :=
66
+ (map_fst sigs sls).first
67
+ lemma map_context_slot : context.Map sls (fun _ x=>x.1.2) :=
68
+ (map_snd sigs sls).first
69
+ lemma map_context_first : context.Map fc (fun _ x=>x.2.1) :=
70
+ map_comp (map_snd _ _) (map_fst _ _)
71
+ lemma map_context_last : context.Map gc (fun _ x=>x.2.2.2) :=
72
+ ((map_snd (rs.function ds) gc).second (c:=fc)).second (c:=sigs.prod sls)
73
+ lemma map_context_noiseTape : context.Map (rs.function ds) (fun _ x=>x.2.2.1) :=
74
+ ((map_fst (rs.function ds) gc).second (c:=fc)).second (c:=sigs.prod sls)
75
+ lemma map_context_valid : context.Map gc (fun _ x=>x.1.1.valid) :=
76
+ map_lambda (map_comp (map_pair map_context_signature.first (map_snd context rs))
77
+ (map_valid.pullback Computable.fst))
78
+ lemma map_context_project : context.Map (rs.function ls) (fun _ x=>x.1.1.project x.1.2) := by
79
+ have hh := (map_project (g:=((signatures.prod slotContexts).prod rights))
80
+ (map_fst signatures slotContexts).first
81
+ (map_snd signatures slotContexts).first (map_snd _ _)).pullback
82
+ (f:=(Prod.fst : Par → ℕ)) Computable.fst
83
+ exact map_lambda (map_comp
84
+ (map_pair (map_pair map_context_signature.first map_context_slot.first) (map_snd context rs)) hh)
85
+ lemma map_context_noise : context.Map gc
86
+ (fun _ x=>MinUncutGames.Reduction.FiniteNoise.realizedNoise x.2.2.1) :=
87
+ map_lambda (map_value_zero (map_apply map_context_noiseTape.first (map_snd context rs)))
88
+ lemma map_localEquation : context.Map keys.equation
89
+ (fun _ x=>x.1.1.equation x.1.2 x.2) := by
90
+ apply (map_rawLocal map_context_valid map_context_project map_context_first
91
+ map_context_last map_context_noise).ofEq
92
+ intro p x
93
+ exact rawLocal_eq x.1.1.valid (x.1.1.project x.1.2) x.2
94
+ end MinUncut.Preprocess.Source
95
+
96
+ noncomputable section
97
+ namespace MinUncut.Preprocess.Syntax
98
+ open MinUncutGames.Foundations.PCP
99
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
100
+ open MinUncutGames.Foundations.Hastad.SourceContexts
101
+ open MinUncut.Costed MinUncut.SourceTemplate UEncoding
102
+ variable {P Q : Type} [Primcodable P] [Primcodable Q] {A : P → Type} {c : UEncoding P A}
103
+ lemma C.precomp {a : Q → AExpr} (ha : C a) {f : P → Q} (hf : Computable f) : C (fun p=>a (f p)) :=
104
+ Computable.comp ha hf
105
+ lemma O.tupleDigit {i : ∀p,A p → ℕ} (hi : c.Out i) : O c (fun p x=>tupleDigit (i p x)) :=
106
+ ((O.fixed (.reg 0)).div ((O.fixed (.reg 2)).pow hi)).mod (O.fixed (.reg 2))
107
+ lemma O.slotWord {i j : ∀p,A p → ℕ} {s : ∀p,A p → Slot}
108
+ (hi : c.Out i) (hs : c.Map (UEncoding.fixed slotEncoding) s) (hj : c.Out j) :
109
+ O c (fun p x=>slotWord (i p x) (s p x) (j p x)) := by
110
+ have hn := (out_code (UEncoding.fixed (P:=P) slotEncoding)).comp hs
111
+ have hc := (out_const c (Computable.const 2)).map₂ hn (ca_mul Computable.fst Computable.snd)
112
+ have hb := hc.map₂ hj (ca_add Computable.fst Computable.snd)
113
+ exact ((O.fixed (.const 3)).add ((O.fixed (.const 6)).mul (O.tupleDigit hi))).add (.const hb) |>.at
114
+
115
+ abbrev unitN : UEncoding ℕ (fun _=>Unit) := UEncoding.fixed Encoding.unit
116
+ lemma c_positiveExpr : C positiveExpr := by
117
+ have hi : ((unitN.prod Source.positions).prod Source.slots).Out (fun _ x=>x.1.2.val) :=
118
+ (out_code Source.positions).second.first
119
+ have hs := map_snd (unitN.prod Source.positions) Source.slots
120
+ have hw := O.slotWord hi hs (out_const _ (Computable.const 1))
121
+ exact (hw.functionExpr (Computable.const 2) |>.functionExpr (Computable.const (2^3))).toC
122
+ lemma c_sameExpr : C sameExpr := by
123
+ let c := (unitN.prod Source.coordinates).prod Source.coordinates
124
+ have ha : c.Map Source.coordinates (fun _ x=>x.1.2) := (map_snd unitN Source.coordinates).first
125
+ have hb : c.Map Source.coordinates (fun _ x=>x.2) := map_snd _ _
126
+ have hai := (out_code Source.positions).comp (map_comp ha (map_fst _ _))
127
+ have hbi := (out_code Source.positions).comp (map_comp hb (map_fst _ _))
128
+ have has := map_comp ha (map_snd _ _)
129
+ have hbs := map_comp hb (map_snd _ _)
130
+ have hzero := out_const c (Computable.const 0)
131
+ have hw := (O.slotWord hai has hzero).eq (O.slotWord hbi hbs hzero)
132
+ exact (hw.functionExpr (Computable.const 2) |>.functionExpr
133
+ (ca_pow (Computable.const 2) (ca_mul Computable.id (Computable.const 3)))).toC
134
+ lemma c_signatureExpr : C signatureExpr := by
135
+ have hconst := C.const (ca_pow (ca_pow (Computable.const 2)
136
+ (ca_mul Computable.id (Computable.const 3))) (ca_mul Computable.id (Computable.const 3)))
137
+ exact c_sameExpr.add (hconst.mul c_positiveExpr)
138
+ lemma O.sourceLookup {u : P → ℕ} (hu : Computable u)
139
+ {f : ∀p,A p × Signature (u p) → ℕ}
140
+ (hf : (c.prod (Source.signatures.pullback u hu)).Out f) :
141
+ O c (fun p x=>signatureLookup (fun s=>f p (x,s))) :=
142
+ (O.fromC (c_signatureExpr.precomp hu)).lookup (out_constantTable hf)
143
+ lemma map_sourceSlot {u : P → ℕ} (hu : Computable u) {s : ∀p,A p → SlotContext (u p)}
144
+ (hs : c.Map (Source.slotContexts.pullback u hu) s) :
145
+ (c.prod (fin u hu)).Map (fixed slotEncoding) (fun p x=>s p x.1 x.2) := by
146
+ have ht : c.Map ((fin u hu).function (fixed slotEncoding)) s := hs
147
+ exact map_apply ht.first (map_snd c (fin u hu))
148
+ lemma O.sourceSampled {u : P → ℕ} (hu : Computable u) {s : ∀p,A p → SlotContext (u p)}
149
+ (hs : c.Map (Source.slotContexts.pullback u hu) s) : O c (fun p x=>sampledExpr (s p x)) := by
150
+ let d := c.prod (fin u hu)
151
+ have hi : d.Out (fun _ x=>x.2.val) := (out_code (fin u hu)).second
152
+ have hx := map_sourceSlot hu hs
153
+ have hw : O d (fun p x=>MinUncut.SourceTemplate.slotWord x.2.val (s p x.1 x.2) 0) :=
154
+ O.slotWord hi hx (out_const d (Computable.const 0))
155
+ have hp : O d (fun _ x=>(AExpr.reg 1).pow x.2.val) := (O.fixed (.reg 1)).pow hi
156
+ have hh : O d (fun p x=>.mul (MinUncut.SourceTemplate.slotWord x.2.val (s p x.1 x.2) 0) ((AExpr.reg 1).pow x.2.val)) := hw.mul hp
157
+ exact hh.sum_fin hu
158
+ end MinUncut.Preprocess.Syntax
159
+
160
+ namespace MinUncut.Preprocess.Face
161
+ open MinUncut.Inner MinUncut.FiniteProof
162
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
163
+ open UEncoding
164
+ open scoped BigOperators
165
+ variable {P : Type} [Primcodable P]
166
+ variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)
167
+ def axes := fin m hm
168
+ def values := fin n hn
169
+ def points := (axes m hm).function (values n hn)
170
+ def rowPairs := (axes m hm).prod (points m n hm hn)
171
+ def rowGood (p : P) (x : Fin (m p) × Point (m p) (n p)) : Bool :=
172
+ decide (x.2 x.1=⟨0,hnpos p⟩)
173
+ lemma map_rowGood : (rowPairs m n hm hn).Map bool (rowGood m n hnpos) := by
174
+ exact map_bool_eq
175
+ (map_apply (map_snd (axes m hm) (points m n hm hn)) (map_fst _ _))
176
+ (map_const (Computable.const 0))
177
+
178
+ def rowEquiv (p : P) : Row (m p) (n p) ≃
179
+ {x:Fin (m p) × Point (m p) (n p) // rowGood m n hnpos p x=true} where
180
+ toFun r := ⟨(r.1,fun j=>if h:j=r.1 then ⟨0,hnpos p⟩ else r.2 ⟨j,h⟩),by simp [rowGood]⟩
181
+ invFun r := ⟨r.val.1,fun j=>r.val.2 j.val⟩
182
+ left_inv r := by
183
+ dsimp only
184
+ refine Sigma.ext (by rfl) ?_
185
+ apply heq_of_eq
186
+ funext j
187
+ exact dite_eq_right j.property
188
+ right_inv r := by
189
+ apply Subtype.ext
190
+ dsimp only
191
+ refine Prod.ext (by rfl) ?_
192
+ funext j
193
+ by_cases h:j=r.val.1
194
+ · subst j
195
+ dsimp only
196
+ split
197
+ · exact ((of_decide_eq_true r.property) : r.val.2 r.val.1=⟨0,hnpos p⟩).symm
198
+ · rename_i hh; exact False.elim (hh rfl)
199
+ · exact dite_eq_right h
200
+
201
+ def rows : UEncoding P (fun p=>Row (m p) (n p)) :=
202
+ ((rowPairs m n hm hn).restrict (rowGood m n hnpos) (map_rowGood m n hm hn hnpos)).ofEquiv
203
+ (rowEquiv m n hnpos)
204
+
205
+ lemma map_faceRow : ((points m n hm hn).prod (axes m hm)).Map (rows m n hm hn hnpos)
206
+ (fun _ x=>⟨x.2,face x.1 x.2⟩) := by
207
+ let pt:=points m n hm hn
208
+ let ax:=axes m hm
209
+ let rs:=rowPairs m n hm hn
210
+ let c:=pt.prod ax
211
+ have hi : c.Map ax (fun _ x=>x.2) := map_snd _ _
212
+ have hx : c.Map pt (fun _ x=>x.1) := map_fst _ _
213
+ have hy : (c.prod ax).Map ax (fun _ x=>x.2) := map_snd _ _
214
+ have hz : (c.prod ax).Map (values n hn) (fun p _=>⟨0,hnpos p⟩) := map_const (Computable.const 0)
215
+ have hw : (c.prod ax).Map (values n hn)
216
+ (fun p x=>if x.2=x.1.2 then ⟨0,hnpos p⟩ else x.1.1 x.2) := by
217
+ apply (map_cond (map_bool_eq hy hi.first) hz
218
+ (map_apply hx.first hy)).ofEq
219
+ intro p x
220
+ simp only [decide_eq_true_eq]
221
+ have hp := map_pair hi (map_lambda hw)
222
+ have hg : ∀p (x : Point (m p) (n p) × Fin (m p)),rowGood m n hnpos p (x.2,fun j=>if j=x.2 then ⟨0,hnpos p⟩ else x.1 j)=true := by
223
+ intro p x
224
+ simp [rowGood]
225
+ have hmk:=map_restrict_mk (map_rowGood m n hm hn hnpos) hp hg
226
+ apply (map_comp hmk (map_from _ (rowEquiv m n hnpos))).ofEq
227
+ intro p x
228
+ refine Sigma.ext (by rfl) ?_
229
+ apply heq_of_eq
230
+ funext j
231
+ exact ite_eq_right j.property
232
+
233
+ lemma map_faceSum : ((rows m n hm hn hnpos).function (field P)).Map
234
+ ((points m n hm hn).function (field P)) (fun p x=>faceSum (m p) (n p) x) := by
235
+ let r:=rows m n hm hn hnpos
236
+ let v:=points m n hm hn
237
+ let ax:=axes m hm
238
+ let c:=(r.function (field P)).prod v
239
+ have hx : (c.prod ax).Map v (fun _ x=>x.1.2) := (map_snd _ _).first
240
+ have hi : (c.prod ax).Map ax (fun _ x=>x.2) := map_snd _ _
241
+ have hr : (c.prod ax).Map r (fun _ x=>⟨x.2,face x.1.2 x.2⟩) :=
242
+ map_comp (map_pair hx hi) (map_faceRow m n hm hn hnpos)
243
+ have hf : (c.prod ax).Map (r.function (field P)) (fun _ x=>x.1.1) := (map_fst _ _).first
244
+ exact map_lambda (map_field_sum (map_apply hf hr))
245
+
246
+ def codeGood (p : P) (x : Point (m p) (n p) → F₂) : Bool :=
247
+ decide (∃f:Row (m p) (n p) → F₂,faceSum (m p) (n p) f=x)
248
+ include hnpos in
249
+ lemma map_codeGood : ((points m n hm hn).function (field P)).Map bool (codeGood m n) := by
250
+ let r:=(rows m n hm hn hnpos).function (field P)
251
+ let v:=(points m n hm hn).function (field P)
252
+ have hh:=map_exists (map_bool_eq
253
+ ((map_faceSum m n hm hn hnpos).second (c:=v)) (map_fst v r))
254
+ apply hh.ofEq
255
+ intro p x
256
+ simp only [codeGood,decide_eq_true_eq]
257
+
258
+ def codeEquiv (p : P) : Code (m p) (n p) ≃
259
+ {x:Point (m p) (n p) → F₂ // codeGood m n p x=true} where
260
+ toFun x := ⟨x.val,by simpa only [codeGood,decide_eq_true_eq] using (LinearMap.mem_range.mp x.property)⟩
261
+ invFun x := ⟨x.val,LinearMap.mem_range.mpr (by simpa only [codeGood,decide_eq_true_eq] using x.property)⟩
262
+ left_inv _ := rfl
263
+ right_inv _ := rfl
264
+
265
+ def codes : UEncoding P (fun p=>Code (m p) (n p)) :=
266
+ (((points m n hm hn).function (field P)).restrict (codeGood m n)
267
+ (map_codeGood m n hm hn hnpos)).ofEquiv (codeEquiv m n)
268
+ lemma map_codeVal : (codes m n hm hn hnpos).Map ((points m n hm hn).function (field P))
269
+ (fun _ x=>x.val) := by
270
+ have hh := map_comp (map_to (((points m n hm hn).function (field P)).restrict (codeGood m n)
271
+ (map_codeGood m n hm hn hnpos)) (codeEquiv m n))
272
+ (map_restrict_val ((points m n hm hn).function (field P)) (codeGood m n)
273
+ (map_codeGood m n hm hn hnpos))
274
+ exact hh.ofEq (by intros; rfl)
275
+ lemma map_codeMk {Γ : P → Type} {g : UEncoding P Γ}
276
+ {f : ∀p,Γ p → Point (m p) (n p) → F₂}
277
+ (hf : g.Map ((points m n hm hn).function (field P)) f)
278
+ (h : ∀p x,∃a:Row (m p) (n p) → F₂,faceSum (m p) (n p) a=f p x) :
279
+ g.Map (codes m n hm hn hnpos) (fun p x=>⟨f p x,LinearMap.mem_range.mpr (h p x)⟩) := by
280
+ have hh:=map_restrict_mk (map_codeGood m n hm hn hnpos) hf
281
+ (by intro p x; simp only [codeGood,decide_eq_true_eq]; exact h p x)
282
+ exact map_comp hh (map_from _ (codeEquiv m n))
283
+
284
+ end MinUncut.Preprocess.Face
285
+
286
+ end
287
+
288
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformEquationOutput.lean ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.UniformOutput
3
+ import OAI.Computability.MinUncut.Graphs.CanonicalSamplerGraph
4
+ import OAI.Computability.MinUncut.Estimates.BlocksEffectivity
5
+
6
+ namespace OAI
7
+
8
+ section
9
+ namespace MinUncut.Preprocess.UEncoding
10
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences MinUncutGames.Reduction.CloneGap
11
+ variable {P : Type} [Primcodable P] {A B : P → Type} {X : Type} [Primcodable X]
12
+ lemma out_elimSum {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,A p → X} {g : ∀p,B p → X}
13
+ (hf : a.Out f) (hg : b.Out g) :
14
+ (a.sum b).Out (fun p x=>Sum.elim (f p) (g p) x) := by
15
+ obtain ⟨f',hfr,hf⟩:=hf
16
+ obtain ⟨g',hgr,hg⟩:=hg
17
+ let sz : P × ℕ → ℕ := fun p=>(a.enc p.1).size
18
+ have hs : Computable sz := a.computableSize.comp Computable.fst
19
+ let raw : P × ℕ → X := fun x=>if x.2<sz x then f' x else g' (x.1,x.2-sz x)
20
+ refine ⟨raw,?_,?_⟩
21
+ · exact (Computable.cond (ca_natLt Computable.snd hs).decide hfr
22
+ (hgr.comp (Computable.fst.pair (ca_sub Computable.snd hs)))).of_eq
23
+ (by intro p; simp only [raw,Bool.cond_eq_ite,decide_eq_true_eq])
24
+ · intro p x
25
+ cases x with
26
+ | inl x =>
27
+ change (if ((a.enc p).code x).val<(a.enc p).size then _ else _)=_
28
+ rw [ite_eq_left ((a.enc p).code x).isLt]
29
+ change f' (p,((a.enc p).code x).val)=f p x
30
+ exact hf p x
31
+ | inr x =>
32
+ change (if (a.enc p).size+((b.enc p).code x).val<(a.enc p).size then _ else _)=_
33
+ rw [ite_eq_right (by omega)]
34
+ change g' (p,(a.enc p).size+((b.enc p).code x).val-(a.enc p).size)=_
35
+ rw [Nat.add_sub_cancel_left,hg]
36
+ rfl
37
+ lemma map_eqTuple (a : UEncoding P A) : a.equation.Map (a.prod (a.prod (a.prod bool)))
38
+ (fun p e=>equationEquiv (A p) e) := map_to _ (fun p=>equationEquiv (A p))
39
+ lemma map_eqFirst (a : UEncoding P A) : a.equation.Map a (fun _ e=>e.first) := by
40
+ have hh := map_comp (map_eqTuple a) (map_fst a (a.prod (a.prod bool)))
41
+ exact hh
42
+ lemma map_eqSecond (a : UEncoding P A) : a.equation.Map a (fun _ e=>e.second) := by
43
+ have hh := map_comp (map_eqTuple a) (map_snd a (a.prod (a.prod bool)))
44
+ have hh := map_comp hh (map_fst a (a.prod bool))
45
+ exact hh
46
+ lemma map_eqThird (a : UEncoding P A) : a.equation.Map a (fun _ e=>e.third) := by
47
+ have hh := map_comp (map_eqTuple a) (map_snd a (a.prod (a.prod bool)))
48
+ have hh := map_comp hh (map_snd a (a.prod bool))
49
+ have hh := map_comp hh (map_fst a bool)
50
+ exact hh
51
+ lemma map_eqRhs (a : UEncoding P A) : a.equation.Map bool (fun _ e=>e.rhs) := by
52
+ have hh := map_comp (map_eqTuple a) (map_snd a (a.prod (a.prod bool)))
53
+ have hh := map_comp hh (map_snd a (a.prod bool))
54
+ have hh := map_comp hh (map_snd a bool)
55
+ exact hh
56
+ end MinUncut.Preprocess.UEncoding
57
+ namespace MinUncut.Preprocess.Source
58
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences MinUncut.SourceTemplate UEncoding
59
+ lemma out_keyTag : keys.Out (fun _ x=>keyTag x) := by
60
+ apply (out_elimSum (out_const fc (Computable.const 0))
61
+ (out_elimSum (out_const gc (Computable.const 1)) (out_const (fixed Encoding.unit) (Computable.const 2)))).ofEq
62
+ intro p x
63
+ cases x with
64
+ | inl _=> rfl
65
+ | inr x=>cases x <;> rfl
66
+ lemma out_keyTable : keys.Out (fun _ x=>keyTable x) := by
67
+ apply (out_elimSum (out_code fc)
68
+ (out_elimSum (out_code gc) (out_const (fixed Encoding.unit) (Computable.const 0)))).ofEq
69
+ intro p x
70
+ cases x with
71
+ | inl _=> rfl
72
+ | inr x=>cases x <;> rfl
73
+ end MinUncut.Preprocess.Source
74
+
75
+ end
76
+ namespace MinUncut.SourceTemplate
77
+ open MinUncutGames.Foundations MinUncutGames.Foundations.Target
78
+ open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences
79
+ open MinUncutGames.Reduction MinUncut.Costed
80
+ noncomputable section
81
+
82
+ def sourceExpressions (u D : ℕ) : List AExpr :=
83
+ (slotContextEncoding u).enumerate.flatMap (fun s=>
84
+ (testTapeEncoding u D).enumerate.flatMap (equationExpressions s))
85
+
86
+ lemma sourceExpressions_eval (F : Formula) {u D : ℕ} (c : ClauseContext F u) :
87
+ (sourceExpressions u D).map (fun e=>e.eval (inputTuple F c))=
88
+ (slotContextEncoding u).enumerate.flatMap (fun s=>
89
+ (testTapeEncoding u D).enumerate.flatMap (fun t=>
90
+ SourceEncoding.equationWords (sourceEquation F u D ((c,s),t)))) := by
91
+ simp only [sourceExpressions,List.map_flatMap,equationExpressions_eval]
92
+
93
+ lemma emitted_source (F : Formula) (u D : ℕ) :
94
+ Blocks.emitted (sourceExpressions u D) (F.clauses.length^u) (Complexity.formulaWords F)=
95
+ (rawSourceList F u D).flatMap SourceEncoding.equationWords := by
96
+ rw [Blocks.emitted,←GraphRegisters.finRange_vals,Hastad.SourceEnumeration.rawSourceList_flatMap]
97
+ have hc : (clauseEncoding F u).enumerate=
98
+ (List.finRange (F.clauses.length^u)).map (clauseEncoding F u).code.symm := by
99
+ exact List.ofFn_eq_map
100
+ rw [hc]
101
+ simp only [List.flatMap_map]
102
+ conv_rhs => erw [List.flatMap_map]
103
+ apply congrArg (List.flatMap · (List.finRange (F.clauses.length^u)))
104
+ funext z
105
+ have he := sourceExpressions_eval (D:=D) F ((clauseEncoding F u).code.symm z)
106
+ simp only [Blocks.block,inputTuple,
107
+ Hastad.SourceEnumeration.testTapeEncoding_enumerate,List.flatMap_assoc,List.flatMap_map,
108
+ sourceEquation] at he ⊢
109
+ erw [Equiv.apply_symm_apply] at he
110
+ exact he
111
+
112
+ def sourceVariableExpr (u : ℕ) : AExpr :=
113
+ .add (.mul ((AExpr.reg 0).pow u) (.const (2^(2^u))))
114
+ (.add (.mul ((AExpr.reg 1).pow u) (.const (2^(8^u)))) (.const 1))
115
+ def sourceCountExpr (u D : ℕ) : AExpr :=
116
+ .div (.mul ((AExpr.reg 1).pow u) (.const (sourceExpressions u D).length)) (.const 4)
117
+ def sourceStageWords (u D : ℕ) (v : List ℕ) : List ℕ :=
118
+ (sourceVariableExpr u).eval v::(sourceCountExpr u D).eval v::
119
+ (Blocks.emitted (sourceExpressions u D) (((AExpr.reg 1).pow u).eval v) v++
120
+ Blocks.retained (sourceExpressions u D) (((AExpr.reg 1).pow u).eval v) v)
121
+ def sourceStageProgram (u D : ℕ) : PolyProgram (sourceStageWords u D) :=
122
+ ((sourceVariableExpr u).program.cons ((sourceCountExpr u D).program.cons
123
+ (Blocks.forward (sourceExpressions u D) ((AExpr.reg 1).pow u)))).ofEq (by intro v; rfl)
124
+
125
+ lemma sourceVariableExpr_eval (F : Formula) (u : ℕ) :
126
+ (sourceVariableExpr u).eval (Complexity.formulaWords F)=nBits F u := by
127
+ simp only [sourceVariableExpr,AExpr.eval,AExpr.eval_pow,Complexity.formulaWords,List.cons_append,List.nil_append,
128
+ List.drop_zero,List.headI_cons,List.drop_succ_cons,nBits_eq]
129
+
130
+ lemma sourceCountExpr_eval (F : Formula) (u D : ℕ) :
131
+ (sourceCountExpr u D).eval (Complexity.formulaWords F)=(rawSourceList F u D).length := by
132
+ have h := congrArg List.length (emitted_source F u D)
133
+ rw [Blocks.length_emitted] at h
134
+ have hl : ((rawSourceList F u D).flatMap SourceEncoding.equationWords).length=
135
+ (rawSourceList F u D).length*4 := by
136
+ simp only [List.length_flatMap,SourceEncoding.equationWords,List.length_cons,List.length_nil]
137
+ simp only [List.map_const',List.sum_replicate,nsmul_eq_mul,Nat.cast_id]
138
+ rw [hl] at h
139
+ simp only [sourceCountExpr,AExpr.eval,AExpr.eval_pow,Complexity.formulaWords,List.cons_append,List.nil_append,
140
+ List.drop_zero,List.headI_cons,List.drop_succ_cons,h]
141
+ omega
142
+
143
+ lemma sourceStageWords_spec (F : Formula) (u D : ℕ) (hD : 0<D) (hne : F.clauses≠[]) :
144
+ ∃junk, sourceStageWords u D (Complexity.formulaWords F)=
145
+ SourceEncoding.inputWords (sourceInput F u D hD)++junk := by
146
+ refine ⟨Blocks.retained (sourceExpressions u D) (F.clauses.length^u) (Complexity.formulaWords F),?_⟩
147
+ unfold sourceStageWords
148
+ rw [sourceVariableExpr_eval,sourceCountExpr_eval]
149
+ have ht : ((AExpr.reg 1).pow u).eval (Complexity.formulaWords F)=F.clauses.length^u := by
150
+ simp only [AExpr.eval_pow,AExpr.eval,Complexity.formulaWords,List.cons_append,List.nil_append,
151
+ List.drop_succ_cons,List.drop_zero,List.headI_cons]
152
+ rw [ht,emitted_source]
153
+ simp only [SourceEncoding.inputWords,sourceInput,sourceList_nonempty F u D hne,
154
+ List.cons_append,List.nil_append]
155
+ end
156
+ end MinUncut.SourceTemplate
157
+
158
+ noncomputable section
159
+ namespace MinUncut.Preprocess.Syntax
160
+ open MinUncutGames.Foundations.PCP
161
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
162
+ open MinUncutGames.Foundations.Hastad.SourceContexts
163
+ open MinUncut.Costed MinUncut.SourceTemplate UEncoding
164
+ variable {P : Type} [Primcodable P] {A : P → Type} {c : UEncoding P A}
165
+ lemma O.sourceAddress {u : P → ℕ} (hu : Computable u) {s : ∀p,A p → SlotContext (u p)}
166
+ (hs : c.Map (Source.slotContexts.pullback u hu) s)
167
+ {f : ∀p,A p × Signature (u p) → LocalKey (u p)}
168
+ (hf : (c.prod (Source.signatures.pullback u hu)).Map
169
+ (Source.keys.pullback (fun p=>(u p,0)) (hu.pair (Computable.const 0))) f) :
170
+ O c (fun p x=>addressExpr (s p x) (fun S=>f p (x,S))) := by
171
+ have hp := hu.pair (Computable.const 0)
172
+ have tag := O.sourceLookup hu ((Source.out_keyTag.pullback hp).comp hf)
173
+ have tab := O.sourceLookup hu ((Source.out_keyTable.pullback hp).comp hf)
174
+ have reg1 : O c (fun p _=>(AExpr.reg 1).pow (u p)) := (O.fixed (.reg 1)).pow (out_const c hu)
175
+ have reg2 : O c (fun p _=>(AExpr.reg 2).pow (u p)) := (O.fixed (.reg 2)).pow (out_const c hu)
176
+ have b2 := ca_pow (Computable.const 2) (ca_pow (Computable.const 2) hu)
177
+ have b8 := ca_pow (Computable.const 2) (ca_pow (Computable.const 8) hu)
178
+ have left := reg1.mul (O.const (out_const c b2))
179
+ have ha := left.add (reg2.mul (O.const (out_const c b8)))
180
+ have hb := left.add (tab.add ((O.const (out_const c b8)).mul (O.fixed (.reg 0))))
181
+ have hc := tab.add ((O.const (out_const c b2)).mul (O.sourceSampled hu hs))
182
+ exact (tag.eq (O.fixed (.const 0))).cond ((tag.eq (O.fixed (.const 1))).cond ha hb) hc
183
+
184
+ abbrev sourceArgs := Source.sls.prod Source.tapes
185
+ lemma map_sourceContext : (sourceArgs.prod Source.sigs).Map Source.context
186
+ (fun _ x=>((x.2,x.1.1),x.1.2)) :=
187
+ map_pair (map_pair (map_snd _ _) ((map_fst _ _).first)) ((map_snd _ _).first)
188
+ lemma out_sourceEquationExpressions : sourceArgs.Out
189
+ (fun _ x=>(equationExpressions x.1 x.2).map (fun e=>e.program.code)) := by
190
+ have hs := map_fst Source.sls Source.tapes
191
+ have he := map_comp map_sourceContext Source.map_localEquation
192
+ have h1 := map_comp he (map_eqFirst Source.keys)
193
+ have h2 := map_comp he (map_eqSecond Source.keys)
194
+ have h3 := map_comp he (map_eqThird Source.keys)
195
+ have hb := (out_boolNat (map_comp he (map_eqRhs Source.keys)))
196
+ have a := O.sourceAddress (c:=sourceArgs) Computable.fst hs h1
197
+ have b := O.sourceAddress (c:=sourceArgs) Computable.fst hs h2
198
+ have d := O.sourceAddress (c:=sourceArgs) Computable.fst hs h3
199
+ have e := O.sourceLookup (c:=sourceArgs) Computable.fst hb
200
+ exact a.cons (b.cons (d.cons (e.cons (out_const sourceArgs (Computable.const [])))))
201
+ lemma c_sourceExpressions : Computable (fun p : Source.Par=>
202
+ (sourceExpressions p.1 p.2).map (fun e=>e.program.code)) := by
203
+ have h := (out_list out_sourceEquationExpressions).enumerate
204
+ apply (Primrec.list_flatten.to_comp.comp (Primrec.list_flatten.to_comp.comp h)).of_eq
205
+ intro p
206
+ simp only [sourceExpressions,List.flatMap_def,List.map_flatten,List.flatten_flatten,List.map_map,Function.comp_def]
207
+ rfl
208
+
209
+ open MinUncut.Costed MinUncut.SourceTemplate MinUncut.CodeEffective
210
+ lemma c_sourceVariableExpr : C sourceVariableExpr := by
211
+ exact ((C.fixed (.reg 0)).pow Computable.id |>.mul (C.const
212
+ (ca_pow (Computable.const 2) (ca_pow (Computable.const 2) Computable.id)))).add
213
+ (((C.fixed (.reg 1)).pow Computable.id |>.mul (C.const
214
+ (ca_pow (Computable.const 2) (ca_pow (Computable.const 8) Computable.id)))).add (C.fixed (.const 1)))
215
+ lemma c_sourceCountExpr : C (fun p : Source.Par=>sourceCountExpr p.1 p.2) := by
216
+ have hl : Computable (fun p : Source.Par=>(sourceExpressions p.1 p.2).length) :=
217
+ (Computable.list_length.comp c_sourceExpressions).of_eq (fun p=>List.length_map ..)
218
+ exact (((C.fixed (.reg 1)).pow Computable.fst).mul (C.const hl)).div (C.fixed (.const 4))
219
+ lemma c_sourceStageCode : Computable (fun p : Source.Par=>(sourceStageProgram p.1 p.2).code) := by
220
+ have hf := p_forwardCode.to_comp.comp c_sourceExpressions ((C.fixed (.reg 1)).pow Computable.fst)
221
+ have hh := computable_cons.comp (c_sourceVariableExpr.precomp Computable.fst)
222
+ (computable_cons.comp c_sourceCountExpr hf)
223
+ apply hh.of_eq
224
+ intro p
225
+ rw [forwardCode_eq]
226
+ rfl
227
+ end MinUncut.Preprocess.Syntax
228
+
229
+ open scoped BigOperators
230
+ namespace MinUncut.Costed.SourceWords
231
+ open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate
232
+ open MinUncut.PathRealization MinUncut.FiniteProof MinUncutGames.Reduction MinUncut.SourceBridge
233
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
234
+ attribute [local instance] Classical.propDecidable
235
+
236
+ variable {t k m n : ℕ} {g : MinUncut.FiniteGaussian.GridData}
237
+
238
+ lemma sum_flatMap_nat {A : Type*} (l : List A) (f : A → List ℕ) :
239
+ (l.flatMap f).sum=(l.map (fun a=>(f a).sum)).sum := by
240
+ induction l with
241
+ | nil => rfl
242
+ | cons a l ih => simp only [List.flatMap_cons,List.sum_append,List.map_cons,List.sum_cons,ih]
243
+
244
+ lemma tupleList_sum (input : SourceEncoding.Input) (f : (Fin t → Fin input.equations.length) → ℕ) :
245
+ ((tupleList input t).map f).sum=∑u,f u := by
246
+ simp only [tupleList,←List.ofFn_eq_map,List.map_ofFn,List.sum_ofFn]
247
+ exact Equiv.sum_comp finFunctionFinEquiv.symm f
248
+
249
+ lemma tupleDemands_failure (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length)
250
+ (E : Enumeration (Index (Fin t) k m n g)) (a : ℚ) (b : MinUncut.Outer.Test → ℚ)
251
+ (σ η : ℚ) (y : Fin (paddedVariableEncoding input.«variables» t).size → Bool) :
252
+ listFailure (tupleDemands input u E a b σ η) y=
253
+ ∑e : Index (Fin t) k m n g,repetitions a b e*failure
254
+ (allDemand (equations input) g σ η (occurrence (equations input) (u,e))) (y ∘ variableCode) := by
255
+ unfold tupleDemands listFailure
256
+ simp only [List.map_flatMap,sum_flatMap_nat,List.map_replicate,List.sum_replicate,
257
+ nsmul_eq_mul,Nat.cast_id,failure_map]
258
+ exact E.sum_values _
259
+
260
+ lemma generatedDemands_failure (input : SourceEncoding.Input)
261
+ (E : Enumeration (Index (Fin t) k m n g)) (a : ℚ) (b : MinUncut.Outer.Test → ℚ)
262
+ (σ η : ℚ) (y : Fin (paddedVariableEncoding input.«variables» t).size → Bool) :
263
+ listFailure (generatedDemands input E a b σ η) y=
264
+ ∑u,∑e : Index (Fin t) k m n g,repetitions a b e*failure
265
+ (allDemand (equations input) g σ η (occurrence (equations input) (u,e))) (y ∘ variableCode) := by
266
+ unfold generatedDemands listFailure
267
+ rw [List.map_flatMap,sum_flatMap_nat]
268
+ change ((tupleList input t).map (fun u=>listFailure (tupleDemands input u E a b σ η) y)).sum=_
269
+ simp only [tupleDemands_failure]
270
+ exact tupleList_sum input _
271
+
272
+ lemma generated_failure_eq {J : ℕ} (P : Parameters J) (input : SourceEncoding.Input)
273
+ [Nonempty (Fin input.equations.length)]
274
+ (E : Enumeration (Index (Fin P.o.t) P.o.k P.d.m P.d.n P.grid))
275
+ (y : Fin (paddedVariableEncoding input.«variables» P.o.t).size → Bool) :
276
+ listFailure (generatedDemands input E (rationalRate J P.d) (rationalBudgets J P.d P.o)
277
+ (rationalSigma J) (rationalEta J)) y=
278
+ listFailure (P.canonicalDemands (equations input)) y := by
279
+ rw [generatedDemands_failure,Parameters.canonicalDemands,listFailure_map,listFailure_demandList]
280
+ have he := Equiv.sum_comp (occurrence (k:=P.o.k) (m:=P.d.m) (n:=P.d.n)
281
+ (g:=P.grid) (equations input)) (fun e=>multiplicity (P.denominator (Fin input.equations.length))
282
+ (P.weight (equations input) e)*failure (P.demand (equations input) e) (y ∘ variableCode))
283
+ rw [Fintype.sum_prod_type] at he
284
+ rw [←he]
285
+ apply Finset.sum_congr rfl
286
+ intro u _
287
+ apply Finset.sum_congr rfl
288
+ intro e _
289
+ congr 1
290
+ exact (occurrence_multiplicity (equations input) (by simpa only [Fintype.card_fin] using P.k_le)
291
+ P.grid_pos.1 P.grid_pos.2 (rationalRate_bounds P.hJ P.d P.hd).1
292
+ (rationalRate_bounds P.hJ P.d P.hd).2 _
293
+ (rationalBudgets_pos P.hJ P.d P.hd P.o P.ho) u e).symm
294
+ end MinUncut.Costed.SourceWords
295
+
296
+ end
297
+
298
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformFaceArray.lean ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.UniformEquation
3
+ import OAI.Computability.MinUncut.Machines.UniformAlphabet
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ noncomputable section
9
+ namespace MinUncut.Preprocess.Alphabet
10
+ open MinUncut.Inner MinUncut.FiniteProof MinUncut.Outer
11
+ open UEncoding
12
+ variable {P : Type} [Primcodable P]
13
+ variable (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool)
14
+ variable (hc : Computable (fun p=>(((MinUncutGames.Foundations.Hastad.SourceOccurrences.Encoding.fin (t p)).function
15
+ MinUncutGames.Foundations.Hastad.SourceOccurrences.Encoding.bool).code (h p)).val))
16
+ variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)
17
+ def arrays : UEncoding P (fun p=>FaceArray (LocalTemplate.Alphabet (h p)) (m p) (n p)) :=
18
+ (Face.rows m n hm hn hnpos).function (forms t ht h hc)
19
+ lemma map_labelCode : ((arrays t ht h hc m n hm hn hnpos).prod (labels t ht h hc)).Map
20
+ (Face.codes m n hm hn hnpos) (fun _ x=>labelCode x.1 x.2) := by
21
+ let r:=Face.rows m n hm hn hnpos
22
+ let a:=arrays t ht h hc m n hm hn hnpos
23
+ let l:=labels t ht h hc
24
+ let c:=a.prod l
25
+ have hb : (c.prod r).Map a (fun _ x=>x.1.1) := (map_fst _ _).first
26
+ have hx : (c.prod r).Map l (fun _ x=>x.1.2) := (map_snd _ _).first
27
+ have he : c.Map (r.function (field P)) (fun _ x r=>(x.1 r) x.2) :=
28
+ map_lambda (map_comp (map_pair (map_apply hb (map_snd _ _)) hx) (map_forms_apply t ht h hc))
29
+ exact Face.map_codeMk m n hm hn hnpos
30
+ (map_comp he (Face.map_faceSum m n hm hn hnpos)) (by intro p x; exact ⟨_,rfl⟩)
31
+ end MinUncut.Preprocess.Alphabet
32
+
33
+ end
34
+ end
35
+
36
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformGrid.lean ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Search.ParameterFields
3
+ import OAI.Computability.MinUncut.Search.UniformRational
4
+ import OAI.Computability.MinUncut.Games.QuestionExpressions
5
+ import OAI.Computability.MinUncut.Estimates.UniformFaceArray
6
+ import OAI.Computability.MinUncut.Machines.UniformDemandAlphabet
7
+ import OAI.Computability.MinUncut.Estimates.UniformProduct
8
+
9
+ namespace OAI
10
+
11
+ noncomputable section
12
+ namespace MinUncut.Preprocess
13
+ open MinUncut.FiniteGaussian
14
+ open scoped BigOperators
15
+ lemma c_coefficient : Computable coefficient :=
16
+ ca_ratDiv (ca_ratPow (ca_const (-1)) Computable.id)
17
+ (ca_ratMul (ca_ratPow (ca_const 2) Computable.id) (ca_ratCast (ca_factorial Computable.id)))
18
+ lemma c_primitive : Computable₂ primitive := by
19
+ have hc : Computable₂ (fun (p : ℕ × ℚ) (j : ℕ)=>coefficient j*p.2^(2*j+1)/(2*j+1)) := by
20
+ apply ca_ratDiv
21
+ · exact ca_ratMul (c_coefficient.comp Computable.snd)
22
+ (ca_ratPow (Computable.snd.comp Computable.fst) (ca_add (ca_mul (ca_const 2) Computable.snd) (ca_const 1)))
23
+ · exact ca_ratAdd (ca_ratMul (ca_const 2) (ca_ratCast Computable.snd)) (ca_const 1)
24
+ exact ((c_rangeSum hc computable_ratAdd).comp Computable.id
25
+ (ca_add (ca_mul (ca_const 2) Computable.fst) (ca_const 1))).of_eq
26
+ (by
27
+ intro p
28
+ dsimp only [primitive]
29
+ rw [←List.sum_toFinset _ List.nodup_range,List.toFinset_range]
30
+ rfl)
31
+ lemma c_qIntegral : Computable (fun p : ℕ × ℚ × ℚ=>qIntegral p.1 p.2.1 p.2.2) :=
32
+ ca_ratSub (c_primitive.comp Computable.fst (Computable.snd.comp Computable.snd))
33
+ (c_primitive.comp Computable.fst (Computable.fst.comp Computable.snd))
34
+ lemma c_endpoint : Computable (fun p : ℚ × ℕ × ℕ=>endpoint p.1 p.2.1 p.2.2) := by
35
+ unfold endpoint
36
+ exact ca_ratAdd (computable_ratNeg.comp Computable.fst)
37
+ (ca_ratDiv (ca_ratMul (ca_ratMul (ca_const 2) Computable.fst)
38
+ (ca_ratCast (Computable.snd.comp Computable.snd)))
39
+ (ca_ratCast (Computable.fst.comp Computable.snd)))
40
+ attribute [local irreducible] endpoint qIntegral primitive
41
+ lemma ca_endpoint {X : Type} [Primcodable X] {t : X → ℚ} {l i : X → ℕ}
42
+ (ht : Computable t) (hl : Computable l) (hi : Computable i) :
43
+ Computable (fun x=>endpoint (t x) (l x) (i x)) := by
44
+ have hh := @Computable.comp X (ℚ × ℕ × ℕ) ℚ _ _ _ _ _ c_endpoint (ht.pair (hl.pair hi))
45
+ exact hh.of_eq (by intro x; rfl)
46
+ lemma ca_qIntegral {X : Type} [Primcodable X] {r : X → ℕ} {a b : X → ℚ}
47
+ (hr : Computable r) (ha : Computable a) (hb : Computable b) :
48
+ Computable (fun x=>qIntegral (r x) (a x) (b x)) := by
49
+ have hh := @Computable.comp X (ℕ × ℚ × ℚ) ℚ _ _ _ _ _ c_qIntegral (hr.pair (ha.pair hb))
50
+ exact hh.of_eq (by intro x; rfl)
51
+ lemma c_midpoint : Computable (fun p : ℚ × ℕ × ℕ=>midpoint p.1 p.2.1 p.2.2) := by
52
+ unfold FiniteGaussian.midpoint
53
+ exact ca_ratDiv (ca_ratAdd c_endpoint
54
+ (ca_endpoint Computable.fst (Computable.fst.comp Computable.snd)
55
+ (ca_add (Computable.snd.comp Computable.snd) (ca_const 1)))) (ca_const 2)
56
+ lemma c_rawCellWeight : Computable (fun p : GridData × ℕ=>
57
+ qIntegral p.1.r (endpoint p.1.T p.1.L p.2) (endpoint p.1.T p.1.L (p.2+1)) /
58
+ qIntegral p.1.r (-p.1.T) p.1.T) := by
59
+ have hr:=c_gridData_r.comp (Computable.fst (α:=GridData) (β:=ℕ))
60
+ have ht:=ca_ratCast (c_gridData_T.comp (Computable.fst (α:=GridData) (β:=ℕ)))
61
+ have hl:=c_gridData_L.comp (Computable.fst (α:=GridData) (β:=ℕ))
62
+ have he : Computable (fun p : GridData × ℕ=>endpoint p.1.T p.1.L p.2) :=
63
+ ca_endpoint ht hl Computable.snd
64
+ have he' : Computable (fun p : GridData × ℕ=>endpoint p.1.T p.1.L (p.2+1)) :=
65
+ ca_endpoint ht hl (ca_add Computable.snd (ca_const 1))
66
+ have ha : Computable (fun p : GridData × ℕ=>qIntegral p.1.r
67
+ (endpoint p.1.T p.1.L p.2) (endpoint p.1.T p.1.L (p.2+1))) :=
68
+ ca_qIntegral hr he he'
69
+ have hb : Computable (fun p : GridData × ℕ=>qIntegral p.1.r (-p.1.T) p.1.T) :=
70
+ ca_qIntegral hr (computable_ratNeg.comp ht) ht
71
+ exact ca_ratDiv ha hb
72
+
73
+ namespace Grid
74
+ open UEncoding MinUncut.Inner
75
+ variable {P : Type} [Primcodable P]
76
+ variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)
77
+ variable (g : P → GridData) (hg : Computable g)
78
+ def coordinates : UEncoding P (fun p=>TestCoordinates (m p) (n p)) :=
79
+ (Face.points m n hm hn).sum ((Face.points m n hm hn).sum (Face.codes m n hm hn hnpos))
80
+ def cells := fin (fun p=>(g p).L) (c_gridData_L.comp hg)
81
+ def samples := (coordinates m n hm hn hnpos).function (cells g hg)
82
+ lemma out_midpoint : (cells g hg).Out (fun p i=>midpoint (g p).T (g p).L i.val) :=
83
+ ((out_const _ (ca_ratCast (c_gridData_T.comp hg))).pair
84
+ ((out_const _ (c_gridData_L.comp hg)).pair (out_code (cells g hg)))).map c_midpoint
85
+ lemma out_cellWeight : (cells g hg).Out (fun p i=>cellWeight (g p).r (g p).T (g p).L i) :=
86
+ ((out_const _ hg).pair (out_code (cells g hg))).map c_rawCellWeight
87
+ lemma out_gridWeight : (samples m n hm hn hnpos g hg).Out (fun p q=>gridWeight (g p) q) := by
88
+ let a:=samples m n hm hn hnpos g hg
89
+ let i:=coordinates m n hm hn hnpos
90
+ exact out_prod ((out_cellWeight g hg).comp (map_apply (map_fst a i) (map_snd a i))) computable_ratMul
91
+ end Grid
92
+ end MinUncut.Preprocess
93
+
94
+ namespace MinUncut.Preprocess.Grid
95
+ open MinUncut.Inner MinUncut.FiniteGaussian UEncoding
96
+ variable {P : Type} [Primcodable P]
97
+ variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)
98
+ variable (g : P → GridData) (hg : Computable g)
99
+ def indices := bool.prod (Face.codes m n hm hn hnpos)
100
+ variable {Γ : P → Type} {c : UEncoding P Γ}
101
+ lemma out_coord {q : ∀p,Γ p → TestCoordinates (m p) (n p) → Fin (g p).L}
102
+ {i : ∀p,Γ p → TestCoordinates (m p) (n p)}
103
+ (hq : c.Map (samples m n hm hn hnpos g hg) q)
104
+ (hi : c.Map (coordinates m n hm hn hnpos) i) :
105
+ c.Out (fun p x=>midpoint (g p).T (g p).L (q p x (i p x))) :=
106
+ (out_midpoint g hg).comp (map_apply hq hi)
107
+ lemma out_sign {z : ∀p,Γ p → Code (m p) (n p)} {i : ∀p,Γ p → Point (m p) (n p)}
108
+ (hz : c.Map (Face.codes m n hm hn hnpos) z) (hi : c.Map (Face.points m n hm hn) i) :
109
+ c.Out (fun p x=>qSign ((z p x).val (i p x))) :=
110
+ (out_field c (map_apply (map_comp hz (Face.map_codeVal m n hm hn hnpos)) hi)).map
111
+ (Primrec.dom_finite qSign).to_comp
112
+ lemma out_scoreSummand (σ : P → ℚ) (hσ : Computable σ) :
113
+ (((samples m n hm hn hnpos g hg).prod (indices m n hm hn hnpos)).prod (Face.points m n hm hn)).Out
114
+ (fun p x=>(midpoint (g p).T (g p).L (x.1.1 (.inl x.2))+
115
+ (if x.1.2.1 then σ p else 0)*midpoint (g p).T (g p).L (x.1.1 (.inr (.inl x.2))))*
116
+ qSign (x.1.2.2.val x.2)) := by
117
+ let s:=samples m n hm hn hnpos g hg
118
+ let z:=indices m n hm hn hnpos
119
+ let pt:=Face.points m n hm hn
120
+ let c:=(s.prod z).prod pt
121
+ have hq : c.Map s (fun _ x=>x.1.1) := (map_fst _ _).first
122
+ have hz : c.Map z (fun _ x=>x.1.2) := (map_snd _ _).first
123
+ have hi : c.Map pt (fun _ x=>x.2) := map_snd _ _
124
+ have hx := out_coord m n hm hn hnpos g hg hq
125
+ (map_comp hi (map_inl pt (pt.sum (Face.codes m n hm hn hnpos))))
126
+ have hy := out_coord m n hm hn hnpos g hg hq
127
+ (map_comp (map_comp hi (map_inl pt (Face.codes m n hm hn hnpos)))
128
+ (map_inr pt (pt.sum (Face.codes m n hm hn hnpos))))
129
+ have hs : c.Out (fun p x=>if x.1.2.1 then σ p else 0) :=
130
+ Out.cond (map_comp hz (map_fst _ _)) (out_const _ hσ) (out_const _ (ca_const 0))
131
+ exact (hx.ratAdd (hs.ratMul hy)).ratMul
132
+ (out_sign m n hm hn hnpos (map_comp hz (map_snd _ _)) hi)
133
+ lemma map_scoreTable (σ η : P → ℚ) (hσ : Computable σ) (hη : Computable η) :
134
+ ((samples m n hm hn hnpos g hg).prod (indices m n hm hn hnpos)).Map bool
135
+ (fun p x=>rationalScoreTable (σ p) (η p)
136
+ (fun i=>midpoint (g p).T (g p).L (x.1 i)) x.2) := by
137
+ let s:=samples m n hm hn hnpos g hg
138
+ let z:=indices m n hm hn hnpos
139
+ let pt:=Face.points m n hm hn
140
+ let co:=Face.codes m n hm hn hnpos
141
+ let c:=s.prod z
142
+ have hq : c.Map s (fun _ x=>x.1) := map_fst _ _
143
+ have hz : c.Map z (fun _ x=>x.2) := map_snd _ _
144
+ have hc : c.Map co (fun _ x=>x.2.2) := map_comp hz (map_snd _ _)
145
+ have hy := out_coord m n hm hn hnpos g hg hq
146
+ (map_comp (map_comp hc (map_inr pt co)) (map_inr pt (pt.sum co)))
147
+ have he : c.Out (fun p x=>if x.2.1 then η p else 0) :=
148
+ Out.cond (map_comp hz (map_fst _ _)) (out_const _ hη) (out_const _ (ca_const 0))
149
+ exact (out_sum (out_scoreSummand m n hm hn hnpos g hg σ hσ) computable_ratAdd).algebraicNonneg
150
+ (he.ratMul hy) (out_const _ (ca_pow hn hm))
151
+ end MinUncut.Preprocess.Grid
152
+
153
+ namespace MinUncut.Preprocess
154
+ open MinUncut.Inner MinUncut.FiniteProof MinUncut.FiniteGaussian MinUncut.Outer
155
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding
156
+ open scoped BigOperators
157
+ attribute [local irreducible] gridWeight
158
+ namespace UEncoding
159
+ variable {P X : Type} [Primcodable P] [Primcodable X] {A : P → Type}
160
+ lemma Out.unit {f : P → X} (hf : (fixed (P:=P) Encoding.unit).Out (fun p _=>f p)) : Computable f := by
161
+ obtain ⟨g,hg,hh⟩:=hf
162
+ exact (hg.comp (Computable.id.pair (Computable.const 0))).of_eq (fun p=>hh p ())
163
+ lemma computable_prod [CommMonoid X] (a : UEncoding P A) [∀p,Fintype (A p)]
164
+ {f : ∀p,A p → X} (hf : a.Out f) (hmul : Computable₂ (fun x y : X=>x*y)) :
165
+ Computable (fun p=>∏x,f p x) := (out_prod hf.second hmul).unit
166
+ end UEncoding
167
+ abbrev tests (P : Type) [Primcodable P] : UEncoding P (fun _=>Test) :=
168
+ fixed SampleEnumeration.tests.encoding
169
+ instance primcodableTest : Primcodable Test :=
170
+ Primcodable.ofEquiv (Fin SampleEnumeration.tests.encoding.size) SampleEnumeration.tests.encoding.code
171
+ namespace Weights
172
+ variable {P : Type} [Primcodable P]
173
+ variable (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool)
174
+ variable (hc : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (h p)).val))
175
+ variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)
176
+ variable (g : P → GridData) (hg : Computable g)
177
+ def localSamples := (Alphabet.arrays t ht h hc m n hm hn hnpos).prod
178
+ ((Alphabet.arrays t ht h hc m n hm hn hnpos).prod ((Face.codes m n hm hn hnpos).prod
179
+ (Grid.samples m n hm hn hnpos g hg)))
180
+ lemma out_rationalRowDensity (a : P → ℚ) (ha : Computable a) :
181
+ ((Alphabet.forms t ht h hc).prod (Alphabet.forms t ht h hc)).Out
182
+ (fun p x=>RowNoise.rationalRowDensity (a p) x.1 x.2) := by
183
+ classical
184
+ let c:=(Alphabet.forms t ht h hc).prod (Alphabet.forms t ht h hc)
185
+ have hc' : Computable (fun p=>Fintype.card (Forms (LocalTemplate.Alphabet (h p)))) :=
186
+ computableCard (Alphabet.forms t ht h hc)
187
+ have hi : c.Out (fun p x=>if x.2=x.1 then (Fintype.card (Forms (LocalTemplate.Alphabet (h p))):ℚ) else 0) := by
188
+ apply (Out.cond (map_bool_eq (map_snd _ _) (map_fst _ _))
189
+ (out_const c (ca_ratCast hc')) (out_const c (ca_const 0))).ofEq
190
+ intro p x
191
+ simp only [decide_eq_true_eq]
192
+ exact ((out_const c (ca_const 1)).ratSub (out_const c ha)).ratMul hi |>.ratAdd (out_const c ha)
193
+ lemma out_rationalDensity (a : P → ℚ) (ha : Computable a) :
194
+ ((Alphabet.arrays t ht h hc m n hm hn hnpos).prod (Alphabet.arrays t ht h hc m n hm hn hnpos)).Out
195
+ (fun p x=>RowNoise.rationalDensity (a p) x.1 x.2) := by
196
+ let ar:=Alphabet.arrays t ht h hc m n hm hn hnpos
197
+ let ro:=Face.rows m n hm hn hnpos
198
+ have hb : ((ar.prod ar).prod ro).Map ar (fun _ x=>x.1.1) := (map_fst _ _).first
199
+ have hc' : ((ar.prod ar).prod ro).Map ar (fun _ x=>x.1.2) := (map_snd _ _).first
200
+ have hr : ((ar.prod ar).prod ro).Map ro (fun _ x=>x.2) := map_snd _ _
201
+ exact out_prod ((out_rationalRowDensity t ht h hc a ha).comp
202
+ (map_pair (map_apply hb hr) (map_apply hc' hr))) computable_ratMul
203
+ lemma out_noiseWeight (a : P → ℚ) (ha : Computable a) :
204
+ (((Alphabet.arrays t ht h hc m n hm hn hnpos).prod
205
+ (Alphabet.arrays t ht h hc m n hm hn hnpos)).prod (tests P)).Out
206
+ (fun p x=>noiseWeight (a p) x.1.1 x.1.2 x.2) := by
207
+ let ar:=Alphabet.arrays t ht h hc m n hm hn hnpos
208
+ let c:=(ar.prod ar).prod (tests P)
209
+ have he : c.Map bool (fun _ x=>decide (x.2=Test.second)) :=
210
+ map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun j=>decide (j=Test.second)) (map_snd _ _)
211
+ exact (Out.cond he (out_rationalDensity t ht h hc m n hm hn hnpos a ha).first
212
+ (out_const c (ca_const 1))).ofEq (by
213
+ intro p x
214
+ cases x.2 <;> simp only [noiseWeight,reduceCtorEq,decide_true,decide_false,Bool.false_eq_true,ite_false,ite_true]
215
+ unfold RowNoise.rationalDensity
216
+ apply Finset.prod_congr rfl
217
+ intro r _
218
+ unfold RowNoise.rationalRowDensity
219
+ split_ifs <;> rfl)
220
+ lemma out_localWeight (a b : P → ℚ) (ha : Computable a) (hb : Computable b) :
221
+ ((localSamples t ht h hc m n hm hn hnpos g hg).prod (tests P)).Out
222
+ (fun p x=>localWeight (g p) (a p) (b p) x.2 x.1) := by
223
+ let s:=localSamples t ht h hc m n hm hn hnpos g hg
224
+ let c:=s.prod (tests P)
225
+ let ar:=Alphabet.arrays t ht h hc m n hm hn hnpos
226
+ have har : Computable (fun p=>(Fintype.card (FaceArray (LocalTemplate.Alphabet (h p)) (m p) (n p)):ℚ)⁻¹) :=
227
+ computable_ratInv.comp (ca_ratCast (computableCard ar))
228
+ have hco : Computable (fun p=>(Fintype.card (Code (m p) (n p)):ℚ)⁻¹) :=
229
+ computable_ratInv.comp (ca_ratCast (computableCard (Face.codes m n hm hn hnpos)))
230
+ have hs : c.Map s (fun _ x=>x.1) := map_fst _ _
231
+ have hB : c.Map ar (fun _ x=>x.1.1) := map_comp hs (map_fst _ _)
232
+ have hC : c.Map ar (fun _ x=>x.1.2.1) := map_comp (map_comp hs (map_snd _ _)) (map_fst _ _)
233
+ have hq : c.Map (Grid.samples m n hm hn hnpos g hg) (fun _ x=>x.1.2.2.2) :=
234
+ map_comp (map_comp (map_comp hs (map_snd _ _)) (map_snd _ _)) (map_snd _ _)
235
+ exact ((((out_const c har).ratMul (out_const c har)).ratMul (out_const c hco)).ratMul
236
+ ((Grid.out_gridWeight m n hm hn hnpos g hg).comp hq)).ratMul
237
+ ((out_noiseWeight t ht h hc m n hm hn hnpos a ha).comp
238
+ (map_pair (map_pair hB hC) (map_snd _ _))) |>.ratDiv (out_const c hb)
239
+ end Weights
240
+ namespace Denominator
241
+ variable {P : Type} [Primcodable P]
242
+ variable (t m n : P → ℕ) (ht : Computable t) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)
243
+ variable (g : P → GridData) (hg : Computable g)
244
+ include ht hm hn hnpos in
245
+ lemma c_faceCardBound : Computable (fun p=>faceCardBound (t p) (m p) (n p)) :=
246
+ ca_pow (ca_pow (ca_const 2) (ca_pow (ca_const 2) (ca_mul (ca_const 3) ht)))
247
+ (computableCard (Face.rows m n hm hn hnpos))
248
+ include hm hn hnpos hg in
249
+ lemma c_gridDenominator : Computable (fun p=>gridDenominator (m p) (n p) (g p)) := by
250
+ let a : UEncoding P (fun p=>TestCoordinates (m p) (n p) → Fin (g p).L) :=
251
+ Grid.samples m n hm hn hnpos g hg
252
+ have hw : a.Out (fun p q=>(gridWeight (g p) q).den) :=
253
+ (Grid.out_gridWeight m n hm hn hnpos g hg).map primrec_ratDen.to_comp
254
+ have hh := @computable_prod P ℕ _ _ (fun p=>TestCoordinates (m p) (n p) → Fin (g p).L)
255
+ _ a (fun _=>inferInstance) _ hw Primrec.nat_mul.to_comp
256
+ apply hh.of_eq
257
+ intro p
258
+ unfold gridDenominator
259
+ apply Finset.prod_congr (by ext; simp)
260
+ intro q _
261
+ rfl
262
+ lemma c_budgetDenominator (b : P → Test → ℚ) (hb : (tests P).Out (fun p j=>b p j)) :
263
+ Computable (fun p=>budgetDenominator (b p)) :=
264
+ computable_prod _ (hb.ratInv.map primrec_ratDen.to_comp) Primrec.nat_mul.to_comp
265
+ include ht hm hn hnpos hg in
266
+ lemma c_innerDenominator (a : P → ℚ) (ha : Computable a)
267
+ (b : P → Test → ℚ) (hb : (tests P).Out (fun p j=>b p j)) :
268
+ Computable (fun p=>innerDenominator (t p) (m p) (n p) (g p) (a p) (b p)) := by
269
+ exact ca_mul (ca_mul (ca_mul (ca_mul (ca_mul
270
+ (ca_factorial (c_faceCardBound t m n ht hm hn hnpos))
271
+ (ca_factorial (c_faceCardBound t m n ht hm hn hnpos)))
272
+ (computableCard (Face.codes m n hm hn hnpos)))
273
+ (c_gridDenominator m n hm hn hnpos g hg))
274
+ (ca_pow (primrec_ratDen.to_comp.comp ha) (computableCard (Face.rows m n hm hn hnpos))))
275
+ (c_budgetDenominator b hb)
276
+ end Denominator
277
+
278
+ open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate MinUncut.FiniteProof MinUncut.FiniteGaussian
279
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding
280
+ namespace UEncoding
281
+ variable {P : Type} [Primcodable P] {A B : P → Type}
282
+ lemma map_testCases {c : UEncoding P A} {b : UEncoding P B} {j : ∀p,A p → Test}
283
+ {f₁ f₂ f₃ f₄ : ∀p,A p → B p} (hj : c.Map (tests P) j)
284
+ (h₁ : c.Map b f₁) (h₂ : c.Map b f₂) (h₃ : c.Map b f₃) (h₄ : c.Map b f₄) :
285
+ c.Map b (fun p x=>match j p x with
286
+ | .first => f₁ p x | .second => f₂ p x | .third => f₃ p x | .fourth => f₄ p x) := by
287
+ have hq (k : Test) : c.Map bool (fun p x=>decide (j p x=k)) :=
288
+ map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun l=>decide (l=k)) hj
289
+ apply (map_cond (hq .first) h₁ (map_cond (hq .second) h₂ (map_cond (hq .third) h₃ h₄))).ofEq
290
+ intro p x
291
+ cases j p x <;> rfl
292
+ end UEncoding
293
+ namespace Queries
294
+ variable {P : Type} [Primcodable P]
295
+ variable (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool)
296
+ variable (hc : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (h p)).val))
297
+ variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)
298
+ def table := (Alphabet.labels t ht h hc).function (bool (P:=P))
299
+ def queryEquiv (p : P) : Query (h p) ≃ Bool × (Alphabet (h p) → Bool) × (Alphabet (h p) → Bool) where
300
+ toFun q := (q.first,q.left,q.right)
301
+ invFun q := ⟨q.1,q.2.1,q.2.2⟩
302
+ left_inv _ := rfl
303
+ right_inv _ := rfl
304
+ def queries : UEncoding P (fun p=>Query (h p)) :=
305
+ (bool.prod ((table t ht h hc).prod (table t ht h hc))).ofEquiv (queryEquiv t h)
306
+ lemma map_first : (queries t ht h hc).Map bool (fun _ q=>q.first) := by
307
+ have hh:=map_comp (map_to (bool.prod ((table t ht h hc).prod (table t ht h hc))) (queryEquiv t h)) (map_fst _ _)
308
+ exact hh
309
+ lemma map_left : (queries t ht h hc).Map (table t ht h hc) (fun _ q=>q.left) := by
310
+ have hh:=map_comp (map_comp (map_to (bool.prod ((table t ht h hc).prod (table t ht h hc))) (queryEquiv t h)) (map_snd _ _)) (map_fst _ _)
311
+ exact hh
312
+ lemma map_right : (queries t ht h hc).Map (table t ht h hc) (fun _ q=>q.right) := by
313
+ have hh:=map_comp (map_comp (map_to (bool.prod ((table t ht h hc).prod (table t ht h hc))) (queryEquiv t h)) (map_snd _ _)) (map_snd _ _)
314
+ exact hh
315
+
316
+ variable {Γ : P → Type} {c : UEncoding P Γ}
317
+ variable {B C : ∀p,Γ p → FaceArray (Alphabet (h p)) (m p) (n p)}
318
+ variable {z : ∀p,Γ p → Code (m p) (n p)} {s : ∀p,Γ p → ScoreIndex (m p) (n p) → Bool}
319
+ variable {j : ∀p,Γ p → Test}
320
+ variable (hB : c.Map (Alphabet.arrays t ht h hc m n hm hn hnpos) B)
321
+ variable (hC : c.Map (Alphabet.arrays t ht h hc m n hm hn hnpos) C)
322
+ variable (hz : c.Map (Face.codes m n hm hn hnpos) z)
323
+ variable (hs : c.Map ((Grid.indices m n hm hn hnpos).function bool) s)
324
+ variable (hj : c.Map (tests P) j)
325
+ include hB hC hz hs hj in
326
+ lemma map_leftEval {a : ∀p,Γ p → Alphabet (h p)} (ha : c.Map (Alphabet.labels t ht h hc) a) :
327
+ c.Map bool (fun p x=>(query (h p) (B p x) (C p x) (z p x) (s p x) (j p x)).left (a p x)) := by
328
+ have hba := map_comp (map_pair hB ha) (Alphabet.map_labelCode t ht h hc m n hm hn hnpos)
329
+ have hca := map_comp (map_pair hC ha) (Alphabet.map_labelCode t ht h hc m n hm hn hnpos)
330
+ have hfalse : c.Map bool (fun _ _=>false) := map_const (Computable.const 0)
331
+ have htrue : c.Map bool (fun _ _=>true) := map_const (Computable.const 1)
332
+ have ha₀ := map_apply hs (map_pair hfalse hba)
333
+ have ha₁ := map_apply hs (map_pair htrue hba)
334
+ have ha₂ := map_apply hs (map_pair htrue hca)
335
+ have ha₃ := map_cond (map_bool_eq hba hz) htrue ha₁
336
+ apply (map_testCases hj ha₀ ha₁ ha₃ ha₂).ofEq
337
+ intro p x
338
+ cases j p x <;> simp only [LocalTemplate.query]
339
+ · change (if decide (labelCode (B p x) (a p x)=z p x) then true else _) = _
340
+ simp only [decide_eq_true_eq,Function.update_apply]
341
+ include hB hC hz hs hj in
342
+ lemma map_rightEval {a : ∀p,Γ p → Alphabet (h p)} (ha : c.Map (Alphabet.labels t ht h hc) a) :
343
+ c.Map bool (fun p x=>(query (h p) (B p x) (C p x) (z p x) (s p x) (j p x)).right (a p x)) := by
344
+ have hba := map_comp (map_pair hB ha) (Alphabet.map_labelCode t ht h hc m n hm hn hnpos)
345
+ have hca := map_comp (map_pair hC ha) (Alphabet.map_labelCode t ht h hc m n hm hn hnpos)
346
+ have hfalse : c.Map bool (fun _ _=>false) := map_const (Computable.const 0)
347
+ have htrue : c.Map bool (fun _ _=>true) := map_const (Computable.const 1)
348
+ have ha₁ := map_apply hs (map_pair htrue hba)
349
+ have ha₂ := map_apply hs (map_pair htrue hca)
350
+ have ha₃ := map_cond (map_bool_eq hba hz) hfalse ha₁
351
+ apply (map_testCases hj ha₁ ha₂ ha₃ ha₂).ofEq
352
+ intro p x
353
+ cases j p x <;> simp only [LocalTemplate.query]
354
+ · change (if decide (labelCode (B p x) (a p x)=z p x) then false else _) = _
355
+ simp only [decide_eq_true_eq,Function.update_apply]
356
+ include hB hC hz hs hj in
357
+ lemma map_query : c.Map (queries t ht h hc)
358
+ (fun p x=>query (h p) (B p x) (C p x) (z p x) (s p x) (j p x)) := by
359
+ have hl := map_lambda (map_leftEval t ht h hc m n hm hn hnpos hB.first hC.first hz.first hs.first hj.first (map_snd _ _))
360
+ have hr := map_lambda (map_rightEval t ht h hc m n hm hn hnpos hB.first hC.first hz.first hs.first hj.first (map_snd _ _))
361
+ have hf : c.Map bool (fun p x=> (query (h p) (B p x) (C p x) (z p x) (s p x) (j p x)).first) := by
362
+ apply (map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun j=>decide (j=Test.fourth)) hj).ofEq
363
+ intro p x
364
+ cases j p x <;> rfl
365
+ exact map_comp (map_pair hf (map_pair hl hr)) (map_from _ (queryEquiv t h))
366
+ end Queries
367
+ end MinUncut.Preprocess
368
+
369
+ namespace MinUncut.Preprocess.Queries
370
+ open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate MinUncut.FiniteProof MinUncut.FiniteGaussian
371
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding
372
+ variable {P : Type} [Primcodable P]
373
+ variable (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool)
374
+ variable (hc : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (h p)).val))
375
+ variable {Γ : P → Type} {c : UEncoding P Γ}
376
+ variable {Q : ∀p,Γ p → Query (h p)} {pos : ∀p,Γ p → Fin (t p) → Fin 3}
377
+ variable {sig : ∀p,Γ p → Signature (Fin (t p))} {x : ∀p,Γ p → Fin (t p) → Triple}
378
+ variable (hQ : c.Map (queries t ht h hc) Q) (hp : c.Map (Alphabet.positionsList t ht) pos)
379
+ variable (hs : c.Map (Alphabet.signatures t ht) sig)
380
+ lemma zero_map : c.Map (Alphabet.labels t ht h hc) (fun _ _=>0) := by
381
+ have hunit : c.Map (fixed Encoding.unit) (fun _ _=>()) := map_const (Computable.const 0)
382
+ have hh := map_comp hunit (Alphabet.map_zeroLabel t ht h hc)
383
+ exact hh
384
+ include hQ hp hs in
385
+ lemma map_leftBase : c.Map bool (fun p a=>(Q p a).leftBase (pos p a) (sig p a)) := by
386
+ have hf:=map_comp hQ (map_first t ht h hc)
387
+ have hl:=map_comp hQ (map_left t ht h hc)
388
+ have ho:=map_comp hs (Alphabet.map_origin t ht)
389
+ have hz:=map_comp (map_pair hp ho) (Alphabet.map_project t ht h hc)
390
+ exact map_cond hf (map_apply hl hz) (map_apply hl (zero_map t ht h hc))
391
+ include hQ hp hs in
392
+ lemma map_leftTableEval (hx : c.Map (Alphabet.ambient t ht) x) :
393
+ c.Map bool (fun p a=>(Q p a).leftTable (pos p a) (sig p a) (x p a)) := by
394
+ have hf:=map_comp hQ (map_first t ht h hc)
395
+ have hl:=map_comp hQ (map_left t ht h hc)
396
+ have hv:=map_comp (map_pair hs hx) (Alphabet.map_valid t ht)
397
+ have hproj:=map_comp (map_pair hp hx) (Alphabet.map_project t ht h hc)
398
+ have hd:=map_comp hx (Alphabet.map_decode t ht h hc)
399
+ have hfalse : c.Map bool (fun _ _=>false) := map_const (Computable.const 0)
400
+ have hbase:=map_leftBase t ht h hc hQ hp hs
401
+ have hzero:=map_apply hl (zero_map t ht h hc)
402
+ apply (map_cond hf (map_cond hv (map_bool_eq hbase (map_apply hl hproj)) hfalse)
403
+ (map_bool_eq hzero (map_apply hl hd))).ofEq
404
+ intro p a
405
+ simp only [Query.leftTable, Bool.beq_eq_decide_eq]
406
+ split_ifs <;> simp_all only [decide_eq_true_eq, ite_true, ite_false]
407
+ include hQ in
408
+ lemma map_rightTableEval (hx : c.Map (Alphabet.ambient t ht) x) :
409
+ c.Map bool (fun p a=>(Q p a).rightTable (x p a)) := by
410
+ have hr:=map_comp hQ (map_right t ht h hc)
411
+ have hd:=map_comp hx (Alphabet.map_decode t ht h hc)
412
+ apply (map_bool_eq (map_apply hr (zero_map t ht h hc)) (map_apply hr hd)).ofEq
413
+ intro p a
414
+ simp only [Query.rightTable, Bool.beq_eq_decide_eq]
415
+ include hQ hp hs in
416
+ lemma map_localSign : c.Map bool (fun p a=>(Q p a).localSign (pos p a) (sig p a)) := by
417
+ have hr:=map_comp hQ (map_right t ht h hc)
418
+ apply (map_bool_eq (map_leftBase t ht h hc hQ hp hs) (map_apply hr (zero_map t ht h hc))).ofEq
419
+ intro p a
420
+ simp only [Query.localSign, Bool.beq_eq_decide_eq]
421
+ include hQ hp hs in
422
+ lemma map_leftTable : c.Map ((Alphabet.ambient t ht).function bool)
423
+ (fun p a=>(Q p a).leftTable (pos p a) (sig p a)) :=
424
+ map_lambda (map_leftTableEval t ht h hc hQ.first hp.first hs.first (map_snd _ _))
425
+ include hQ in
426
+ lemma map_rightTable : c.Map ((Alphabet.ambient t ht).function bool)
427
+ (fun p a=>(Q p a).rightTable) :=
428
+ map_lambda (map_rightTableEval t ht h hc hQ.first (map_snd _ _))
429
+ end MinUncut.Preprocess.Queries
430
+
431
+ open scoped BigOperators
432
+ namespace MinUncut.Costed.SourceWords
433
+ open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate
434
+ open MinUncutGames.Reduction MinUncut.SourceBridge
435
+
436
+ def signatureExpr (t : ℕ) : AExpr :=
437
+ AExpr.add
438
+ (AExpr.sum (List.ofFn fun i : Fin t =>
439
+ AExpr.mul
440
+ (AExpr.sum (List.ofFn fun p : Fin 3 =>
441
+ AExpr.mul
442
+ (AExpr.sum (List.ofFn fun q : Fin 3 =>
443
+ AExpr.mul (.eq (slotExpr i.val p.val) (slotExpr i.val q.val))
444
+ (.const (2^q.val))))
445
+ (.const ((2^3)^p.val))))
446
+ (.const (((2^3)^3)^i.val))))
447
+ (.mul (.const (((2^3)^3)^t))
448
+ (.sum (List.ofFn fun i : Fin t=> .mul (slotExpr i.val 3) (.const (2^i.val)))))
449
+
450
+ lemma signatureExpr_eval {t : ℕ} (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) :
451
+ (signatureExpr t).eval (inputTuple input u)=
452
+ ((signatureEncoding t).code (signature (fun j=>equations input (u j)))).val := by
453
+ rw [signature_code]
454
+ simp only [signatureExpr,AExpr.eval,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn,
455
+ slotExpr_name,slotExpr_rhs,signatureNumber,signature]
456
+ congr 1
457
+ apply Finset.sum_congr rfl
458
+ intro i _
459
+ congr 1
460
+ apply Finset.sum_congr rfl
461
+ intro p _
462
+ congr 1
463
+ apply Finset.sum_congr rfl
464
+ intro q _
465
+ congr 1
466
+ by_cases h : (equations input (u i)).names p=(equations input (u i)).names q
467
+ · simp only [h,decide_true,Bool.toNat_true,ite_true]
468
+ · have h' : ((equations input (u i)).names p).val≠((equations input (u i)).names q).val :=
469
+ fun e=>h (Fin.ext e)
470
+ simp only [h,h',decide_false,Bool.toNat_false,ite_false]
471
+
472
+ def signatureLookup {t : ℕ} (f : Signature (Fin t) → ℕ) : AExpr :=
473
+ (signatureExpr t).lookup (constantTable (signatureEncoding t) f)
474
+ lemma signatureLookup_eval {t : ℕ} (input : SourceEncoding.Input)
475
+ (u : Fin t → Fin input.equations.length) (f : Signature (Fin t) → ℕ) :
476
+ (signatureLookup f).eval (inputTuple input u)=f (signature (fun j=>equations input (u j))) := by
477
+ exact constantTable_eval _ _ _ _ _ (signatureExpr_eval input u)
478
+
479
+ end MinUncut.Costed.SourceWords
480
+
481
+ end
482
+
483
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformOutput.lean ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.UniformRestrict
3
+ import OAI.Computability.MinUncut.Estimates.UniformTransport
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ namespace MinUncut.Preprocess.UEncoding
9
+ variable {P Q : Type} [Primcodable P] [Primcodable Q] {A : P → Type}
10
+ {X : Type} [Primcodable X]
11
+ lemma Out.pullback {a : UEncoding P A} {g : ∀p,A p → X}
12
+ (hg : a.Out g) {f : Q → P} (hf : Computable f) :
13
+ (a.pullback f hf).Out (fun q x=>g (f q) x) := by
14
+ obtain ⟨g',hgr,hg⟩:=hg
15
+ exact ⟨fun q=>g' (f q.1,q.2),hgr.comp ((hf.comp Computable.fst).pair Computable.snd),
16
+ by intro q x; exact hg (f q) x⟩
17
+ lemma Out.cons {a : UEncoding P A} {f : ∀p,A p → X} {g : ∀p,A p → List X}
18
+ (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>f p x::g p x) :=
19
+ hf.map₂ hg Primrec.list_cons.to_comp
20
+ lemma out_boolNat {a : UEncoding P A} {f : ∀p,A p → Bool} (hf : a.Map bool f) :
21
+ a.Out (fun p x=>(f p x).toNat) :=
22
+ (hf.out false).map (Primrec.dom_bool Bool.toNat).to_comp
23
+ end MinUncut.Preprocess.UEncoding
24
+
25
+ end
26
+
27
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformProduct.lean ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.UniformRestrict
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ namespace MinUncut.Preprocess
8
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
9
+ open scoped BigOperators
10
+ variable {P X : Type} [Primcodable P] [Primcodable X] [CommMonoid X]
11
+ lemma c_rangeProd {f : P → ℕ → X} (hf : Computable₂ f)
12
+ (hmul : Computable₂ (fun x y : X=>x*y)) :
13
+ Computable₂ (fun p n=>((List.range n).map (f p)).prod) := by
14
+ have hh := Computable.nat_rec (α:=P × ℕ) (σ:=X) Computable.snd
15
+ (Computable.const 1)
16
+ (hmul.comp (Computable.snd.comp Computable.snd)
17
+ (hf.comp (Computable.fst.comp Computable.fst) (Computable.fst.comp Computable.snd))).to₂
18
+ exact hh.of_eq (by
19
+ intro p
20
+ induction p.2 with
21
+ | zero => rfl
22
+ | succ n ih => simp only [List.range_succ,List.map_append,List.map_singleton,List.prod_append,
23
+ List.prod_singleton,ih])
24
+
25
+ namespace UEncoding
26
+ variable {A B Γ : P → Type}
27
+ lemma out_prod {g : UEncoding P Γ} {a : UEncoding P A}
28
+ [∀p,Fintype (A p)] {f : ∀p,Γ p × A p → X} (hf : (g.prod a).Out f)
29
+ (hmul : Computable₂ (fun x y : X=>x*y)) :
30
+ g.Out (fun p s=>∏x,f p (s,x)) := by
31
+ obtain ⟨f',hf',hf⟩:=hf
32
+ let raw : (P × ℕ) → ℕ → X := fun q i=>f' (q.1,q.2*(a.enc q.1).size+i)
33
+ have hr : Computable₂ raw := by
34
+ unfold raw
35
+ exact hf'.comp ((Computable.fst.comp Computable.fst).pair
36
+ (ca_add (ca_mul (Computable.snd.comp Computable.fst)
37
+ (a.computableSize.comp (Computable.fst.comp Computable.fst))) Computable.snd))
38
+ refine ⟨fun q=>((List.range (a.enc q.1).size).map (raw q)).prod,
39
+ (c_rangeProd hr hmul).comp Computable.id (a.computableSize.comp Computable.fst),?_⟩
40
+ intro p s
41
+ dsimp only
42
+ have he : ((a.enc p).enumerate.map (fun x=>f p (s,x))).prod=∏x,f p (s,x) := by
43
+ classical
44
+ have ht : (a.enc p).enumerate.toFinset=Finset.univ := by ext x; simp [(a.enc p).mem_enumerate x]
45
+ rw [← List.prod_toFinset _ (a.enc p).nodup_enumerate,ht]
46
+ rw [←he,Encoding.enumerate,List.ofFn_eq_map,List.map_map]
47
+ rw [←finRange_values ((a.enc p).size),List.map_map]
48
+ apply congrArg List.prod
49
+ apply List.map_congr_left
50
+ intro i hi
51
+ have hh:=hf p (s,(a.enc p).code.symm i)
52
+ change f' (p,(((g.enc p).prod (a.enc p)).code (s,(a.enc p).code.symm i)).val)=_ at hh
53
+ rw [prod_code,Equiv.apply_symm_apply] at hh
54
+ exact hh
55
+
56
+ omit [Primcodable X] [CommMonoid X] in
57
+ lemma computableCard (a : UEncoding P A) [∀p,Fintype (A p)] : Computable (fun p=>Fintype.card (A p)) :=
58
+ a.computableSize.of_eq (fun p=>(Fintype.card_congr (a.enc p).code).trans (Fintype.card_fin _)|>.symm)
59
+
60
+ end UEncoding
61
+ end MinUncut.Preprocess
62
+
63
+ end
64
+
65
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformRestrict.lean ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.UniformBoolean
3
+
4
+ namespace OAI
5
+
6
+ namespace MinUncut.Preprocess
7
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
8
+ namespace UEncoding
9
+ variable {P : Type} [Primcodable P] {A B Γ : P → Type}
10
+
11
+ def goodCodes (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) : List ℕ :=
12
+ (List.range (a.enc p).size).filter (fun n=>if h:n<(a.enc p).size then b p ((a.enc p).code.symm ⟨n,h⟩) else false)
13
+ lemma goodCodes_nodup (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) :
14
+ (goodCodes a b p).Nodup := List.nodup_range.filter _
15
+ lemma mem_goodCodes (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) (n : ℕ) :
16
+ n∈goodCodes a b p ↔ ∃h:n<(a.enc p).size,b p ((a.enc p).code.symm ⟨n,h⟩)=true := by
17
+ simp only [goodCodes,List.mem_filter,List.mem_range]
18
+ by_cases hn:n<(a.enc p).size <;> simp [hn]
19
+ lemma original_mem_goodCodes (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) (x : A p) :
20
+ ((a.enc p).code x).val∈goodCodes a b p ↔ b p x=true := by
21
+ rw [mem_goodCodes]
22
+ simp only [Equiv.symm_apply_apply,Fin.eta]
23
+ exact ⟨fun h=>h.2,fun h=>⟨((a.enc p).code x).isLt,h⟩⟩
24
+
25
+ lemma computable_goodCodes (a : UEncoding P A) (b : ∀p,A p → Bool) (hb : a.Map bool b) :
26
+ Computable (goodCodes a b) := by
27
+ obtain ⟨f,hf,h⟩:=hb
28
+ have hr : Computable₂ (fun p n=>if f (p,n)=1 then [n] else []) := by
29
+ exact (Computable.cond (Primrec.eq.decide.to_comp.comp hf (Computable.const 1))
30
+ (Computable.list_cons.comp Computable.snd (Computable.const []))
31
+ (Computable.const [])).of_eq (by intro q; simp)
32
+ have hh := Primrec.list_flatten.to_comp.comp ((c_rangeMap hr).comp Computable.id a.computableSize)
33
+ apply hh.of_eq
34
+ intro p
35
+ change (List.range (a.enc p).size).flatMap _=_
36
+ rw [show goodCodes a b p=(List.range (a.enc p).size).flatMap
37
+ (fun n=>if (if h:n<(a.enc p).size then b p ((a.enc p).code.symm ⟨n,h⟩) else false) then [n] else []) by
38
+ unfold goodCodes
39
+ generalize List.range (a.enc p).size = xs
40
+ induction xs with
41
+ | nil => rfl
42
+ | cons x xs ih => simp only [List.filter_cons,List.flatMap_cons,ih]; split_ifs <;> simp_all]
43
+ apply List.flatMap_congr
44
+ intro n hn
45
+ have hn' : n<(a.enc p).size := List.mem_range.mp hn
46
+ have ht := h p ((a.enc p).code.symm ⟨n,hn'⟩)
47
+ simp only [Equiv.apply_symm_apply] at ht
48
+ dsimp only [id]
49
+ simp only [dite_eq_left hn',ht]
50
+ change (if (Encoding.bool.code _).val=1 then _ else _) = _
51
+ rw [bool_code]
52
+ cases b p ((a.enc p).code.symm ⟨n,hn'⟩) <;> rfl
53
+
54
+ def restrictEquiv (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) :
55
+ {x:A p // b p x=true} ≃ {n:ℕ // n∈goodCodes a b p} where
56
+ toFun x := ⟨((a.enc p).code x.val).val,(original_mem_goodCodes a b p x).mpr x.property⟩
57
+ invFun n := ⟨(a.enc p).code.symm ⟨n.val,((mem_goodCodes a b p n).mp n.property).choose⟩,
58
+ ((mem_goodCodes a b p n).mp n.property).choose_spec⟩
59
+ left_inv x := by apply Subtype.ext; exact (a.enc p).code.symm_apply_apply x.val
60
+ right_inv n := by apply Subtype.ext; exact congrArg Fin.val ((a.enc p).code.apply_symm_apply _)
61
+
62
+ def restrict (a : UEncoding P A) (b : ∀p,A p → Bool) (hb : a.Map bool b) :
63
+ UEncoding P (fun p=>{x:A p // b p x=true}) where
64
+ enc p := ⟨(goodCodes a b p).length,(restrictEquiv a b p).trans
65
+ ((goodCodes_nodup a b p).getEquiv (goodCodes a b p)).symm⟩
66
+ computableSize := Computable.list_length.comp (computable_goodCodes a b hb)
67
+
68
+ lemma restrict_code (a : UEncoding P A) (b : ∀p,A p → Bool) (hb : a.Map bool b)
69
+ (p : P) (x : {x:A p // b p x=true}) :
70
+ (((a.restrict b hb).enc p).code x).val=(goodCodes a b p).idxOf (((a.enc p).code x.val).val) := rfl
71
+
72
+ lemma map_restrict_val (a : UEncoding P A) (b : ∀p,A p → Bool) (hb : a.Map bool b) :
73
+ (a.restrict b hb).Map a (fun _ x=>x.val) := by
74
+ refine ⟨fun q=>((goodCodes a b q.1)[q.2]?).getD 0,?_,?_⟩
75
+ · exact Primrec.option_getD_default.to_comp.comp
76
+ (Computable.list_getElem?.comp ((computable_goodCodes a b hb).comp Computable.fst) Computable.snd)
77
+ · intro p x
78
+ dsimp only
79
+ rw [restrict_code,List.getElem?_idxOf (by exact (original_mem_goodCodes a b p x).mpr x.property)]
80
+ rfl
81
+
82
+ lemma map_restrict_mk {g : UEncoding P Γ} {a : UEncoding P A} {b : ∀p,A p → Bool}
83
+ (hb : a.Map bool b) {f : ∀p,Γ p → A p} (hf : g.Map a f)
84
+ (h : ∀p x,b p (f p x)=true) :
85
+ g.Map (a.restrict b hb) (fun p x=>⟨f p x,h p x⟩) := by
86
+ obtain ⟨f',hf',he⟩:=hf
87
+ refine ⟨fun q=>(goodCodes a b q.1).idxOf (f' q),?_,?_⟩
88
+ · exact Primrec.list_idxOf.to_comp.comp hf' ((computable_goodCodes a b hb).comp Computable.fst)
89
+ · intro p x
90
+ dsimp only
91
+ rw [he,restrict_code]
92
+
93
+ end UEncoding
94
+
95
+ namespace UEncoding
96
+ variable {P : Type} [Primcodable P] {A B Γ : P → Type}
97
+ variable {X Y Z : Type} [Primcodable X] [Primcodable Y] [Primcodable Z]
98
+
99
+ def Out (a : UEncoding P A) (f : ∀p,A p → X) : Prop :=
100
+ ∃g : P × ℕ → X, Computable g ∧ ∀p x,g (p,((a.enc p).code x).val)=f p x
101
+ lemma Out.ofEq {a : UEncoding P A} {f g : ∀p,A p → X} (hf : a.Out f)
102
+ (h : ∀p x,f p x=g p x) : a.Out g := by
103
+ obtain ⟨f',hr,hh⟩:=hf
104
+ exact ⟨f',hr,fun p x=>(hh p x).trans (h p x)⟩
105
+ lemma out_const (a : UEncoding P A) {f : P → X} (hf : Computable f) :
106
+ a.Out (fun p _=>f p) := ⟨_,hf.comp Computable.fst,by intros; rfl⟩
107
+ lemma out_code (a : UEncoding P A) : a.Out (fun p x=>((a.enc p).code x).val) :=
108
+ ⟨Prod.snd,Computable.snd,by intros; rfl⟩
109
+ lemma Out.comp {a : UEncoding P A} {b : UEncoding P B}
110
+ {f : ∀p,A p → B p} {g : ∀p,B p → X} (hg : b.Out g) (hf : a.Map b f) :
111
+ a.Out (fun p x=>g p (f p x)) := by
112
+ obtain ⟨f',hrf,hf⟩:=hf
113
+ obtain ⟨g',hrg,hg⟩:=hg
114
+ exact ⟨fun q=>g' (q.1,f' q),hrg.comp (Computable.fst.pair hrf),
115
+ by intro p x; dsimp only; rw [hf,hg]⟩
116
+ lemma Out.map {a : UEncoding P A} {f : ∀p,A p → X} (hf : a.Out f)
117
+ {g : X → Y} (hg : Computable g) : a.Out (fun p x=>g (f p x)) := by
118
+ obtain ⟨f',hrf,hf⟩:=hf
119
+ exact ⟨_,hg.comp hrf,by intro p x; dsimp only; rw [hf]⟩
120
+ lemma Out.map₂ {a : UEncoding P A} {f : ∀p,A p → X} {g : ∀p,A p → Y}
121
+ (hf : a.Out f) (hg : a.Out g) {op : X → Y → Z} (hop : Computable₂ op) :
122
+ a.Out (fun p x=>op (f p x) (g p x)) := by
123
+ obtain ⟨f',hrf,hf⟩:=hf
124
+ obtain ⟨g',hrg,hg⟩:=hg
125
+ exact ⟨_,hop.comp hrf hrg,by intro p x; dsimp only; rw [hf,hg]⟩
126
+ lemma Out.pair {a : UEncoding P A} {f : ∀p,A p → X} {g : ∀p,A p → Y}
127
+ (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>(f p x,g p x)) :=
128
+ hf.map₂ hg (Computable.fst.pair Computable.snd)
129
+ lemma Out.first {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,A p → X}
130
+ (hf : a.Out f) : (a.prod b).Out (fun p x=>f p x.1) := hf.comp (map_fst a b)
131
+ lemma Out.second {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,A p → X}
132
+ (hf : a.Out f) : (b.prod a).Out (fun p x=>f p x.2) := hf.comp (map_snd b a)
133
+
134
+ lemma out_list {g : UEncoding P Γ} {a : UEncoding P A}
135
+ {f : ∀p,Γ p × A p → X} (hf : (g.prod a).Out f) :
136
+ g.Out (fun p s=>(a.enc p).enumerate.map (fun x=>f p (s,x))) := by
137
+ obtain ⟨f',hf',hf⟩:=hf
138
+ let raw : (P × ℕ) → ℕ → X := fun q i=>f' (q.1,q.2*(a.enc q.1).size+i)
139
+ have hr : Computable₂ raw := by
140
+ unfold raw
141
+ exact hf'.comp ((Computable.fst.comp Computable.fst).pair
142
+ (ca_add (ca_mul (Computable.snd.comp Computable.fst)
143
+ (a.computableSize.comp (Computable.fst.comp Computable.fst))) Computable.snd))
144
+ refine ⟨fun q=>(List.range (a.enc q.1).size).map (raw q),
145
+ (c_rangeMap hr).comp Computable.id (a.computableSize.comp Computable.fst),?_⟩
146
+ intro p s
147
+ dsimp only
148
+ rw [Encoding.enumerate,List.ofFn_eq_map,List.map_map]
149
+ rw [←finRange_values ((a.enc p).size),List.map_map]
150
+ apply List.map_congr_left
151
+ intro i hi
152
+ have hh:=hf p (s,(a.enc p).code.symm i)
153
+ change f' (p,(((g.enc p).prod (a.enc p)).code (s,(a.enc p).code.symm i)).val)=_ at hh
154
+ rw [prod_code,Equiv.apply_symm_apply] at hh
155
+ exact hh
156
+
157
+ lemma Out.enumerate {a : UEncoding P A} {f : ∀p,A p → X} (hf : a.Out f) :
158
+ Computable (fun p=>(a.enc p).enumerate.map (f p)) := by
159
+ have hh:=out_list (g:=fixed Encoding.unit) hf.second
160
+ obtain ⟨h,hr,he⟩:=hh
161
+ exact (hr.comp (Computable.id.pair (Computable.const 0))).of_eq (fun p=>he p ())
162
+
163
+ lemma fixed_out (a : Encoding X) (x₀ : X) : (fixed (P:=P) a).Out (fun _ x=>x) := by
164
+ let table:=a.enumerate
165
+ refine ⟨fun q=>(table[q.2]?).getD x₀,?_,?_⟩
166
+ · exact Primrec.option_getD.to_comp.comp
167
+ ((Primrec.list_getElem?₁ table).to_comp.comp Computable.snd) (Computable.const x₀)
168
+ · intro p x
169
+ dsimp only
170
+ change (a.enumerate[(a.code x).val]?).getD x₀=x
171
+ simp [Encoding.enumerate,(a.code x).isLt]
172
+ lemma Map.out {a : UEncoding P A} {b : Encoding X} {f : ∀p,A p → X}
173
+ (hf : a.Map (fixed b) f) (x₀ : X) : a.Out f := (fixed_out b x₀).comp hf
174
+ lemma Out.toBool {a : UEncoding P A} {f : ∀p,A p → Bool} (hf : a.Out f) : a.Map bool f := by
175
+ obtain ⟨f',hr,h⟩:=hf
176
+ refine ⟨fun q=>(f' q).toNat,(Primrec.dom_bool Bool.toNat).to_comp.comp hr,?_⟩
177
+ intro p x
178
+ dsimp only
179
+ rw [h]
180
+ exact (bool_code _).symm
181
+ lemma Out.toFin {a : UEncoding P A} {n : P → ℕ} (hn : Computable n)
182
+ {f : ∀p,A p → Fin (n p)} (hf : a.Out (fun p x=>(f p x).val)) :
183
+ a.Map (fin n hn) f := hf
184
+ lemma Out.cond {a : UEncoding P A} {c : ∀p,A p → Bool} {f g : ∀p,A p → X}
185
+ (hc : a.Map bool c) (hf : a.Out f) (hg : a.Out g) :
186
+ a.Out (fun p x=>if c p x then f p x else g p x) := by
187
+ obtain ⟨c',hcr,hc⟩:=hc.out false
188
+ obtain ⟨f',hfr,hf⟩:=hf
189
+ obtain ⟨g',hgr,hg⟩:=hg
190
+ exact ⟨_,Computable.cond hcr hfr hgr,by intro p x; simp only [hc,hf,hg,Bool.cond_eq_ite]⟩
191
+
192
+ end UEncoding
193
+ end MinUncut.Preprocess
194
+
195
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformSets.lean ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.UniformAlgebra
3
+ import OAI.Computability.MinUncut.Encoding.DerivedResolver
4
+ import OAI.Computability.MinUncut.Estimates.UniformOutput
5
+
6
+ namespace OAI
7
+
8
+ section
9
+ noncomputable section
10
+ namespace MinUncut.Preprocess
11
+ open MinUncut.Outer MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding
12
+ open scoped BigOperators
13
+ def maskEquiv (t : ℕ) : Finset (Fin t) ≃ (Fin t → Bool) where
14
+ toFun := hiddenSet
15
+ invFun h := Finset.univ.filter (fun i=>h i=true)
16
+ left_inv S := by ext i; simp [hiddenSet]
17
+ right_inv h := by funext i; simp [hiddenSet]
18
+ def setEncoding (t : ℕ) : Encoding (Finset (Fin t)) :=
19
+ ⟨2^t,(maskEquiv t).trans (((Encoding.fin t).function Encoding.bool).code)⟩
20
+ def rawSet (t z : ℕ) : Finset (Fin t) :=
21
+ (setEncoding t).code.symm ⟨z%(2^t),Nat.mod_lt _ (pow_pos (by decide) _)⟩
22
+ lemma rawSet_code (t : ℕ) (S : Finset (Fin t)) :
23
+ rawSet t ((setEncoding t).code S).val=S := by
24
+ unfold rawSet
25
+ have hs : ((setEncoding t).code S).val<2^t := ((setEncoding t).code S).isLt
26
+ simp only [Nat.mod_eq_of_lt hs]
27
+ exact (setEncoding t).code.symm_apply_apply S
28
+ lemma rawSet_maskCode (t z : ℕ) :
29
+ (((Encoding.fin t).function Encoding.bool).code (hiddenSet (rawSet t z))).val=z%(2^t) := by
30
+ change ((setEncoding t).code ((setEncoding t).code.symm _)).val=_
31
+ rw [Equiv.apply_symm_apply]
32
+ variable {P : Type} [Primcodable P]
33
+ def sets (t : P → ℕ) (ht : Computable t) : UEncoding P (fun p=>Finset (Fin (t p))) where
34
+ enc p := setEncoding (t p)
35
+ computableSize := ca_pow (ca_const 2) ht
36
+ lemma map_hidden (t : P → ℕ) (ht : Computable t) :
37
+ (sets t ht).Map ((fin t ht).function bool) (fun _ S=>hiddenSet S) :=
38
+ ⟨Prod.snd,Computable.snd,by intros; rfl⟩
39
+ lemma out_setCard (t : P → ℕ) (ht : Computable t) :
40
+ (sets t ht).Out (fun _ S=>S.card) := by
41
+ have hmask:=map_hidden t ht
42
+ have hi := map_apply hmask.first (map_snd (sets t ht) (fin t ht))
43
+ apply (out_sum (out_boolNat hi) Primrec.nat_add.to_comp).ofEq
44
+ intro p S
45
+ have he : ∀i:Fin (t p), (hiddenSet S i).toNat=if i∈S then 1 else 0 := by
46
+ intro i
47
+ by_cases hi:i∈S <;> simp [hiddenSet,hi]
48
+ simp only [he]
49
+ simp
50
+ lemma c_rawHidden (t : P → ℕ) (ht : Computable t) (z : P → ℕ) (hz : Computable z) :
51
+ Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code
52
+ (hiddenSet (rawSet (t p) (z p)))).val) :=
53
+ (ca_mod hz (ca_pow (ca_const 2) ht)).of_eq (by intro p; exact (rawSet_maskCode _ _).symm)
54
+ end MinUncut.Preprocess
55
+
56
+ end
57
+ end
58
+
59
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/UniformTransport.lean ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Encoding.UniformEncoding
3
+
4
+ namespace OAI
5
+
6
+ namespace MinUncut.Preprocess
7
+ open MinUncutGames.Foundations.Hastad.SourceOccurrences
8
+ namespace UEncoding
9
+ variable {P Q : Type} [Primcodable P] [Primcodable Q] {A B C Γ : P → Type}
10
+
11
+ def ofEquiv (a : UEncoding P A) (e : ∀p,B p ≃ A p) : UEncoding P B where
12
+ enc p := ⟨(a.enc p).size,(e p).trans (a.enc p).code⟩
13
+ computableSize := a.computableSize
14
+ lemma map_to (a : UEncoding P A) (e : ∀p,B p ≃ A p) :
15
+ (a.ofEquiv e).Map a (fun p x=>e p x) :=
16
+ ⟨Prod.snd,Computable.snd,by intros; rfl⟩
17
+ lemma map_from (a : UEncoding P A) (e : ∀p,B p ≃ A p) :
18
+ a.Map (a.ofEquiv e) (fun p x=>(e p).symm x) :=
19
+ ⟨Prod.snd,Computable.snd,by intro p x; exact congrArg Fin.val ((a.enc p).code.congr_arg ((e p).apply_symm_apply x)).symm⟩
20
+
21
+ def pullback (a : UEncoding P A) (f : Q → P) (hf : Computable f) : UEncoding Q (fun q=>A (f q)) where
22
+ enc q := a.enc (f q)
23
+ computableSize := a.computableSize.comp hf
24
+ lemma Map.pullback {a : UEncoding P A} {b : UEncoding P B} {g : ∀p,A p → B p}
25
+ (hg : a.Map b g) {f : Q → P} (hf : Computable f) :
26
+ (a.pullback f hf).Map (b.pullback f hf) (fun q x=>g (f q) x) := by
27
+ obtain ⟨g',hg',hg⟩:=hg
28
+ refine ⟨fun q=>g' (f q.1,q.2),hg'.comp ((hf.comp Computable.fst).pair Computable.snd),?_⟩
29
+ intro q x
30
+ exact hg (f q) x
31
+
32
+ lemma Map.first {a : UEncoding P A} {b : UEncoding P B} {c : UEncoding P C}
33
+ {f : ∀p,A p → B p} (hf : a.Map b f) :
34
+ (a.prod c).Map b (fun p x=>f p x.1) := map_comp (map_fst a c) hf
35
+ lemma Map.second {a : UEncoding P A} {b : UEncoding P B} {c : UEncoding P C}
36
+ {f : ∀p,A p → B p} (hf : a.Map b f) :
37
+ (c.prod a).Map b (fun p x=>f p x.2) := map_comp (map_snd c a) hf
38
+
39
+ lemma Map.specialize {g : UEncoding P Γ} {a : UEncoding P A} {b : UEncoding P B}
40
+ {f : ∀p,Γ p × A p → B p} (hf : (g.prod a).Map b f)
41
+ {x : ∀p,Γ p → A p} (hx : g.Map a x) :
42
+ g.Map b (fun p s=>f p (s,x p s)) := map_comp (map_pair (map_id g) hx) hf
43
+
44
+ end UEncoding
45
+
46
+ namespace UEncoding
47
+ variable {P : Type} [Primcodable P] {A B C Γ : P → Type}
48
+ variable {p : P}
49
+ def sum (a : UEncoding P A) (b : UEncoding P B) : UEncoding P (fun p=>A p ⊕ B p) where
50
+ enc p := (a.enc p).sum (b.enc p)
51
+ computableSize := ca_add a.computableSize b.computableSize
52
+ omit [Primcodable P] in
53
+ lemma sum_code_inl (a : Encoding (A p)) (b : Encoding (B p)) (x : A p) :
54
+ ((a.sum b).code (Sum.inl x)).val=(a.code x).val := rfl
55
+ omit [Primcodable P] in
56
+ lemma sum_code_inr (a : Encoding (A p)) (b : Encoding (B p)) (x : B p) :
57
+ ((a.sum b).code (Sum.inr x)).val=a.size+(b.code x).val := rfl
58
+ lemma map_inl (a : UEncoding P A) (b : UEncoding P B) :
59
+ a.Map (a.sum b) (fun _ x=>Sum.inl x) :=
60
+ ⟨Prod.snd, Computable.snd, by intro p x; rfl⟩
61
+ lemma map_inr (a : UEncoding P A) (b : UEncoding P B) :
62
+ b.Map (a.sum b) (fun _ x=>Sum.inr x) :=
63
+ ⟨fun q=>(a.enc q.1).size+q.2,
64
+ ca_add (a.computableSize.comp Computable.fst) Computable.snd,
65
+ by intro p x; rfl⟩
66
+ lemma map_case {g : UEncoding P Γ} {a : UEncoding P A} {b : UEncoding P B}
67
+ {c : UEncoding P C} {f : ∀p,Γ p × A p → C p} {h : ∀p,Γ p × B p → C p}
68
+ (hf : (g.prod a).Map c f) (hh : (g.prod b).Map c h) :
69
+ (g.prod (a.sum b)).Map c (fun p x=>Sum.elim (fun y=>f p (x.1,y)) (fun y=>h p (x.1,y)) x.2) := by
70
+ obtain ⟨f',hf',hf⟩:=hf
71
+ obtain ⟨h',hh',hh⟩:=hh
72
+ let leftSize : P × ℕ → ℕ := fun q=>(a.enc q.1).size
73
+ let rightSize : P × ℕ → ℕ := fun q=>(b.enc q.1).size
74
+ let tag : P × ℕ → ℕ := fun q=>q.2 % (leftSize q+rightSize q)
75
+ let ctxt : P × ℕ → ℕ := fun q=>q.2 / (leftSize q+rightSize q)
76
+ have hl : Computable leftSize := a.computableSize.comp Computable.fst
77
+ have hr : Computable rightSize := b.computableSize.comp Computable.fst
78
+ have ht : Computable tag := ca_mod Computable.snd (ca_add hl hr)
79
+ have hc : Computable ctxt := ca_div Computable.snd (ca_add hl hr)
80
+ let raw : P × ℕ → ℕ := fun q=>if tag q<leftSize q then f' (q.1,ctxt q*leftSize q+tag q)
81
+ else h' (q.1,ctxt q*rightSize q+(tag q-leftSize q))
82
+ have hraw : Computable raw :=
83
+ (Computable.cond (ca_natLt ht hl).decide (hf'.comp (Computable.fst.pair (ca_add (ca_mul hc hl) ht)))
84
+ (hh'.comp (Computable.fst.pair (ca_add (ca_mul hc hr) (ca_sub ht hl))))).of_eq (by intro q; simp only [raw,Bool.cond_eq_ite,decide_eq_true_eq])
85
+ refine ⟨raw,hraw,?_⟩
86
+ intro p ⟨s,z⟩
87
+ have hz : (((a.enc p).sum (b.enc p)).code z).val<(a.enc p).size+(b.enc p).size :=
88
+ (((a.enc p).sum (b.enc p)).code z).isLt
89
+ have hs : 0<(a.enc p).size+(b.enc p).size := by exact Nat.zero_lt_of_lt hz
90
+ have hc' : ctxt (p,(((g.enc p).prod ((a.enc p).sum (b.enc p))).code (s,z)).val)=((g.enc p).code s).val := by
91
+ simp only [ctxt,leftSize,rightSize]
92
+ change ((((a.enc p).sum (b.enc p)).code z).val+((a.enc p).size+(b.enc p).size)*((g.enc p).code s).val)/
93
+ ((a.enc p).size+(b.enc p).size)=_
94
+ rw [Nat.add_mul_div_left _ _ hs,Nat.div_eq_of_lt hz,Nat.zero_add]
95
+ have ht' : tag (p,(((g.enc p).prod ((a.enc p).sum (b.enc p))).code (s,z)).val)=(((a.enc p).sum (b.enc p)).code z).val := by
96
+ simp only [tag,leftSize,rightSize]
97
+ change ((((a.enc p).sum (b.enc p)).code z).val+((a.enc p).size+(b.enc p).size)*((g.enc p).code s).val)%
98
+ ((a.enc p).size+(b.enc p).size)=_
99
+ rw [Nat.add_mul_mod_self_left,Nat.mod_eq_of_lt hz]
100
+ change raw (p,(((g.enc p).prod ((a.enc p).sum (b.enc p))).code (s,z)).val)=_
101
+ dsimp only [raw]
102
+ rw [hc',ht']
103
+ cases z with
104
+ | inl x =>
105
+ have he:=hf p (s,x)
106
+ change f' (p,(((g.enc p).prod (a.enc p)).code (s,x)).val)=_ at he
107
+ rw [prod_code] at he
108
+ simpa only [show (((a.enc p).sum (b.enc p)).code (.inl x)).val=((a.enc p).code x).val from rfl,
109
+ leftSize,rightSize,((a.enc p).code x).isLt,ite_true,Sum.elim_inl] using he
110
+ | inr x =>
111
+ have he:=hh p (s,x)
112
+ change h' (p,(((g.enc p).prod (b.enc p)).code (s,x)).val)=_ at he
113
+ rw [prod_code] at he
114
+ simpa only [show (((a.enc p).sum (b.enc p)).code (.inr x)).val=(a.enc p).size+((b.enc p).code x).val from rfl,
115
+ leftSize,rightSize,Nat.add_sub_cancel_left,Nat.not_lt.mpr (Nat.le_add_right _ _),ite_false,Sum.elim_inr] using he
116
+ end UEncoding
117
+ end MinUncut.Preprocess
118
+
119
+ end OAI
lean/OAI/Computability/MinUncut/Estimates/WeightedTestLaw.lean ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Search.FiniteAverageBounds
3
+ import OAI.Computability.MinUncut.Estimates.LiteralTestQueries
4
+ import OAI.Computability.MinUncut.Analysis.RationalRowNoise
5
+
6
+ namespace OAI
7
+
8
+ noncomputable section
9
+ open scoped BigOperators
10
+ namespace MinUncut.Outer
11
+ open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof
12
+ attribute [local instance] Classical.propDecidable coordsDecEq
13
+ variable {Name I : Type*} [Fintype I] {m n : ℕ}
14
+
15
+ abbrev LocalSample (A : Type*) {V : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] (m n : ℕ) (g : GridData) :=
16
+ FaceArray A m n × FaceArray A m n × Code m n × (TestCoordinates m n → Fin g.L)
17
+
18
+ def noiseWeight {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
19
+ (a : ℚ) (B C : FaceArray A m n) : Test → ℚ
20
+ | .second => RowNoise.rationalDensity a B C
21
+ | _ => 1
22
+
23
+ def localWeight {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
24
+ (g : GridData) (a b : ℚ) (j : Test) (p : LocalSample A m n g) : ℚ :=
25
+ (Fintype.card (FaceArray A m n):ℚ)⁻¹ * (Fintype.card (FaceArray A m n):ℚ)⁻¹ *
26
+ (Fintype.card (Code m n):ℚ)⁻¹ * gridWeight g p.2.2.2 * noiseWeight a p.1 p.2.1 j / b
27
+
28
+ lemma sum_invcard_mul {X : Type*} [Fintype X] (f : X → ℝ) :
29
+ (∑ x, (Fintype.card X:ℝ)⁻¹*f x)=𝔼 x, f x := by
30
+ rw [← Finset.mul_sum,Fintype.expect_eq_sum_div_card,mul_comm,div_eq_mul_inv]
31
+
32
+ lemma localWeight_nonneg {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
33
+ (g : GridData) (hT : 0<g.T) (hL : 0<g.L) {a b : ℚ} (ha : 0≤a) (ha1 : a≤1)
34
+ (hb : 0<b) (j : Test) (p : LocalSample A m n g) : 0≤localWeight g a b j p := by
35
+ have hg := (gridWeight_pos g hT hL p.2.2.2).le
36
+ have hn : 0≤noiseWeight a p.1 p.2.1 j := by
37
+ cases j with
38
+ | second => exact RowNoise.rationalDensity_nonneg ha ha1 _ _
39
+ | first => exact zero_le_one
40
+ | third => exact zero_le_one
41
+ | fourth => exact zero_le_one
42
+ exact div_nonneg (mul_nonneg (mul_nonneg (mul_nonneg
43
+ (mul_nonneg (inv_nonneg.mpr (Nat.cast_nonneg _)) (inv_nonneg.mpr (Nat.cast_nonneg _)))
44
+ (inv_nonneg.mpr (Nat.cast_nonneg _))) hg) hn) hb.le
45
+
46
+ lemma localWeight_sum {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
47
+ (g : GridData) (a b : ℚ) (j : Test) (F : LocalSample A m n g → ℝ) :
48
+ (∑ p, (localWeight g a b j p:ℝ)*F p)=
49
+ (𝔼 B, 𝔼 C, 𝔼 z, ∑ q : TestCoordinates m n → Fin g.L,
50
+ (gridWeight g q:ℝ)*(noiseWeight a B C j:ℝ)*F (B,C,z,q))/(b:ℝ) := by
51
+ simp only [localWeight,Rat.cast_div,Rat.cast_mul,Rat.cast_inv,Rat.cast_natCast,
52
+ Fintype.sum_prod_type,Fintype.expect_eq_sum_div_card]
53
+ simp only [div_eq_mul_inv,Finset.sum_mul]
54
+ apply Finset.sum_congr rfl
55
+ intro B _
56
+ apply Finset.sum_congr rfl
57
+ intro C _
58
+ apply Finset.sum_congr rfl
59
+ intro z _
60
+ apply Finset.sum_congr rfl
61
+ intro q _
62
+ ring
63
+
64
+ lemma noiseWeight_cast (U : I → Equation Name) (h : I → Bool) (pos : I → Fin 3)
65
+ (a : ℚ) (B C : FaceArray (SecondAlphabet (secondQuestion U h pos)) m n) :
66
+ (noiseWeight a B C .second:ℝ)=RowNoise.density a B C :=
67
+ RowNoise.rationalDensity_cast a B C
68
+
69
+ lemma localTest_mean (f : ProofFamily Name I) (U : I → Equation Name) (h : I → Bool)
70
+ (pos : I → Fin 3) (g : GridData) (a σ η : ℚ) (j : Test) :
71
+ (𝔼 B, 𝔼 C, 𝔼 z, ∑ q : TestCoordinates m n → Fin g.L,
72
+ (gridWeight g q:ℝ)*(noiseWeight a B C j:ℝ)*
73
+ testFunctional f U h pos B C z (rationalScoreTable σ η (fun i => midpoint g.T g.L (q i))) j)=
74
+ match j with
75
+ | .first => finiteFirst (m := m) (n := n) g (f.second (secondQuestion U h pos)) σ η
76
+ | .second => finiteSecond (m := m) (n := n) g (f.second (secondQuestion U h pos)) a σ η
77
+ | .third => finiteThird (m := m) (n := n) g (f.second (secondQuestion U h pos)) σ η
78
+ | .fourth => finiteFourth (m := m) (n := n) g (projection U h pos)
79
+ (f.first U) (f.second (secondQuestion U h pos)) σ η := by
80
+ cases j
81
+ · simp only [noiseWeight,Rat.cast_one,mul_one,testFunctional,Fintype.expect_const,
82
+ finiteFirst,tableAverage]
83
+ · simp only [noiseWeight,RowNoise.rationalDensity_cast,testFunctional,Fintype.expect_const,
84
+ finiteSecond,tableAverage]
85
+ congr 1
86
+ funext B
87
+ congr 1
88
+ funext C
89
+ rw [Finset.mul_sum]
90
+ exact Finset.sum_congr rfl (fun q _ => by ring)
91
+ · simp only [noiseWeight,Rat.cast_one,mul_one,testFunctional,Fintype.expect_const,
92
+ finiteThird,tableAverage]
93
+ · simp only [noiseWeight,Rat.cast_one,mul_one,testFunctional,Fintype.expect_const,
94
+ finiteFourth,tableAverage]
95
+ end MinUncut.Outer
96
+
97
+ namespace MinUncut.Outer
98
+ open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothness
99
+ attribute [local instance] Classical.propDecidable coordsDecEq
100
+ variable {Name I S : Type*} [Fintype I] [Fintype S] {m n k : ℕ}
101
+
102
+ instance localSampleFintype {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
103
+ (m n : ℕ) (g : GridData) : Fintype (LocalSample A m n g) := by
104
+ unfold LocalSample
105
+ infer_instance
106
+
107
+ abbrev OuterSample (I S : Type*) [Fintype I] (k : ℕ) :=
108
+ FixedSets I k × (I → S) × (I → Fin 3)
109
+
110
+ def sampleFirst (equations : S → Equation Name) (o : OuterSample I S k) : I → Equation Name :=
111
+ fun i => equations (o.2.1 i)
112
+ def sampleHidden (o : OuterSample I S k) : I → Bool := hiddenSet o.1.val
113
+
114
+ abbrev sampleSecond (equations : S → Equation Name) (o : OuterSample I S k) : I → SecondQuestion Name :=
115
+ secondQuestion (sampleFirst equations o) (sampleHidden o) o.2.2
116
+
117
+ abbrev Elementary (equations : S → Equation Name) (k m n : ℕ) (g : GridData) :=
118
+ Σ o : OuterSample I S k, LocalSample (SecondAlphabet (sampleSecond equations o)) m n g
119
+
120
+ instance elementaryFintype (equations : S → Equation Name) (k m n : ℕ) (g : GridData) :
121
+ Fintype (Elementary (I := I) equations k m n g) := by
122
+ unfold Elementary
123
+ infer_instance
124
+
125
+ def elementaryWeight (equations : S → Equation Name) (g : GridData) (a b : ℚ) (j : Test)
126
+ (e : Elementary (I := I) equations k m n g) : ℚ :=
127
+ (Fintype.card (OuterSample I S k):ℚ)⁻¹*localWeight g a b j e.2
128
+
129
+ def elementaryQuery (equations : S → Equation Name) (g : GridData) (σ η : ℚ) (j : Test)
130
+ (e : Elementary (I := I) equations k m n g) : QueryDemand (A := FamilyAlphabet (Name := Name) (I := I)) :=
131
+ testQuery (sampleFirst equations e.1) (sampleHidden e.1) e.1.2.2 e.2.1 e.2.2.1 e.2.2.2.1
132
+ (rationalScoreTable σ η (fun i => midpoint g.T g.L (e.2.2.2.2 i))) j
133
+
134
+ lemma elementaryWeight_nonneg (equations : S → Equation Name) (g : GridData)
135
+ (hT : 0<g.T) (hL : 0<g.L) {a b : ℚ} (ha : 0≤a) (ha1 : a≤1) (hb : 0<b)
136
+ (j : Test) (e : Elementary (I := I) equations k m n g) :
137
+ 0≤elementaryWeight equations g a b j e :=
138
+ mul_nonneg (inv_nonneg.mpr (Nat.cast_nonneg _)) (localWeight_nonneg g hT hL ha ha1 hb j e.2)
139
+
140
+ lemma expect_prod_type {X Y : Type*} [Fintype X] [Fintype Y] (f : X × Y → ℝ) :
141
+ (𝔼 p, f p)=𝔼 x, 𝔼 y, f (x,y) := by
142
+ simp only [Fintype.expect_eq_sum_div_card,Fintype.sum_prod_type,Fintype.card_prod,Nat.cast_mul,
143
+ Finset.sum_div,div_div]
144
+ rw [mul_comm (Fintype.card X:ℝ)]
145
+
146
+ lemma outer_weight_sum (equations : S → Equation Name) (F : EdgeStatistic Name I) :
147
+ (∑ o : OuterSample I S k, (Fintype.card (OuterSample I S k):ℝ)⁻¹*
148
+ F (sampleFirst equations o) (sampleHidden o) o.2.2)=edgeMean equations k F := by
149
+ rw [sum_invcard_mul,expect_prod_type]
150
+ simp only [expect_prod_type,edgeMean,sampleHidden]
151
+ rfl
152
+
153
+ lemma elementary_weighted_sum (equations : S → Equation Name) (g : GridData) (a b σ η : ℚ)
154
+ (j : Test) (f : ProofFamily Name I) :
155
+ (∑ e : Elementary (I := I) equations k m n g,
156
+ (elementaryWeight equations g a b j e:ℝ)*((elementaryQuery equations g σ η j e).failure f.queryAnswer:ℝ))=
157
+ edgeMean equations k (fun U h pos =>
158
+ (match j with
159
+ | .first => finiteFirst (m := m) (n := n) g (f.second (secondQuestion U h pos)) σ η
160
+ | .second => finiteSecond (m := m) (n := n) g (f.second (secondQuestion U h pos)) a σ η
161
+ | .third => finiteThird (m := m) (n := n) g (f.second (secondQuestion U h pos)) σ η
162
+ | .fourth => finiteFourth (m := m) (n := n) g (projection U h pos)
163
+ (f.first U) (f.second (secondQuestion U h pos)) σ η)/(b:ℝ)) := by
164
+ change (∑ e : Sigma _, _) = _
165
+ rw [Fintype.sum_sigma]
166
+ simp only [elementaryWeight,Rat.cast_mul,Rat.cast_inv,Rat.cast_natCast,mul_assoc,← Finset.mul_sum]
167
+ trans ∑ o : OuterSample I S k, (Fintype.card (OuterSample I S k):ℝ)⁻¹*
168
+ ((𝔼 B, 𝔼 C, 𝔼 z, ∑ q : TestCoordinates m n → Fin g.L,
169
+ (gridWeight g q:ℝ)*(noiseWeight a B C j:ℝ)*testFunctional f
170
+ (sampleFirst equations o) (sampleHidden o) o.2.2 B C z
171
+ (rationalScoreTable σ η (fun i => midpoint g.T g.L (q i))) j)/(b:ℝ))
172
+ · rw [Finset.mul_sum]
173
+ apply Finset.sum_congr rfl
174
+ intro o _
175
+ congr 1
176
+ rw [localWeight_sum]
177
+ simp only [elementaryQuery]
178
+ simp_rw [testQuery_failure]
179
+ · simp_rw [localTest_mean]
180
+ rw [sum_invcard_mul,expect_prod_type]
181
+ simp only [expect_prod_type,edgeMean,sampleHidden]
182
+ cases j <;> rfl
183
+ end MinUncut.Outer
184
+
185
+ end
186
+
187
+ end OAI
lean/OAI/Computability/MinUncut/Games/Actual.lean ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.PCP.Folding
3
+ import OAI.Computability.MinUncut.Encoding.BinaryLinear
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ namespace MinUncutGames.Reduction.ActualSource
9
+
10
+ open MinUncutGames.Integration.BinaryLinear
11
+
12
+ structure Source where
13
+ «variables» : Nat
14
+ occurrences : Nat
15
+ nonempty : 0 < occurrences
16
+ equation : Fin occurrences → CloneGap.Equation (Fin «variables»)
17
+
18
+ def Source.sourceList (S : Source) : List (CloneGap.Equation (Fin S.«variables»)) :=
19
+ List.ofFn S.equation
20
+
21
+ def Source.ofList {n : Nat} (es : List (CloneGap.Equation (Fin n)))
22
+ (hne : es ≠ []) : Source where
23
+ «variables» := n
24
+ occurrences := es.length
25
+ nonempty := List.length_pos_iff.mpr hne
26
+ equation := es.get
27
+
28
+ @[simp] theorem Source.sourceList_ofList {n : Nat}
29
+ (es : List (CloneGap.Equation (Fin n))) (hne : es ≠ []) :
30
+ (Source.ofList es hne).sourceList = es := by
31
+ exact List.ofFn_getElem
32
+
33
+ @[simp] theorem Source.sourceList_length (S : Source) :
34
+ S.sourceList.length = S.occurrences := by simp [Source.sourceList]
35
+
36
+ theorem Source.sourceList_nonempty (S : Source) : S.sourceList ≠ [] := by
37
+ intro h
38
+ have hp := S.nonempty
39
+ have hn := S.sourceList_length
40
+ rw [h] at hn
41
+ simp only [List.length_nil] at hn
42
+ omega
43
+
44
+ instance sourceIndexNonempty (S : Source) : Nonempty (Fin S.occurrences) :=
45
+ ⟨⟨0, S.nonempty⟩⟩
46
+
47
+ def Source.satisfied (S : Source) (A : Fin S.«variables» → Bool)
48
+ (i : Fin S.occurrences) : Bool := CloneGap.satisfied (S.equation i) A
49
+
50
+ def Source.failure (S : Source) (A : Fin S.«variables» → Bool) : ℚ :=
51
+ Finset.univ.expect (fun i => if S.satisfied A i then (0 : ℚ) else 1)
52
+
53
+ def Source.DistinctNames (S : Source) : Prop :=
54
+ ∀ i, (S.equation i).first ≠ (S.equation i).second ∧
55
+ (S.equation i).first ≠ (S.equation i).third ∧
56
+ (S.equation i).second ≠ (S.equation i).third
57
+
58
+ abbrev Alphabet (s : Nat) := MinUncutGames.Integration.BinaryLinear.Vector s
59
+ abbrev Ambient (s d : Nat) := Alphabet s × MinUncutGames.Integration.BinaryLinear.Vector d
60
+
61
+ def alphabetEmbedding (s d : Nat) : Alphabet s →ₗ[F2] Ambient s d :=
62
+ LinearMap.inl F2 (Alphabet s) (MinUncutGames.Integration.BinaryLinear.Vector d)
63
+
64
+ @[simp] theorem alphabetEmbedding_apply (s d : Nat) (c : Alphabet s) :
65
+ alphabetEmbedding s d c = (c, 0) := rfl
66
+
67
+ structure SplitGadget (s d : Nat) where
68
+ f : Ambient s d → Alphabet s
69
+ equivariant : ∀ (x : Ambient s d) (c : Alphabet s), f (x + (c, 0)) = f x + c
70
+ NoiseIndex : Type
71
+ noiseFintype : Fintype NoiseIndex
72
+ noiseNonempty : Nonempty NoiseIndex
73
+ noise : NoiseIndex → Ambient s d
74
+
75
+ attribute [instance] SplitGadget.noiseFintype SplitGadget.noiseNonempty
76
+
77
+ def SplitGadget.stabilityError {s d : Nat} (g : SplitGadget s d) : ℚ :=
78
+ Finset.univ.expect (fun xv : Ambient s d × g.NoiseIndex =>
79
+ if g.f (xv.1 + g.noise xv.2) = g.f xv.1 then (0 : ℚ) else 1)
80
+
81
+ def SplitGadget.kernelError {s d p : Nat} (g : SplitGadget s d)
82
+ (S : Ambient s d →ₗ[F2] MinUncutGames.Integration.BinaryLinear.Vector p) : ℚ :=
83
+ Finset.univ.expect (fun i => if S (g.noise i) = 0 then (1 : ℚ) else 0)
84
+
85
+ theorem SplitGadget.stabilityError_nonneg {s d : Nat} (g : SplitGadget s d) :
86
+ 0 ≤ g.stabilityError := by
87
+ apply Finset.expect_nonneg
88
+ intro x _
89
+ split <;> norm_num
90
+
91
+ theorem SplitGadget.stabilityError_le_one {s d : Nat} (g : SplitGadget s d) :
92
+ g.stabilityError ≤ 1 := by
93
+ apply Finset.expect_le Finset.univ_nonempty
94
+ intro x _
95
+ split <;> norm_num
96
+
97
+ end MinUncutGames.Reduction.ActualSource
98
+
99
+ end
100
+ section
101
+ namespace MinUncutGames.Reduction.Incidence
102
+
103
+ universe u v
104
+ variable {Variable : Type u} {Index : Type v}
105
+
106
+ structure Triple where
107
+ first : Bool
108
+ second : Bool
109
+ third : Bool
110
+ deriving DecidableEq
111
+
112
+ def parity (a : Triple) : Bool := (a.first.xor a.second).xor a.third
113
+
114
+ def matchingSlots (a b : Triple) : Nat :=
115
+ (if a.first = b.first then 1 else 0) +
116
+ (if a.second = b.second then 1 else 0) +
117
+ (if a.third = b.third then 1 else 0)
118
+
119
+ def acceptedSlots (a b : Triple) (rhs : Bool) : Nat :=
120
+ if parity a = rhs then matchingSlots a b else 0
121
+
122
+ def failedEquation (b : Triple) (rhs : Bool) : Nat :=
123
+ if parity b = rhs then 0 else 1
124
+
125
+ def bestResponse (b : Triple) (rhs : Bool) : Triple :=
126
+ if parity b = rhs then b else { b with first := !b.first }
127
+
128
+ theorem local_count_bound (a b : Triple) (rhs : Bool) :
129
+ acceptedSlots a b rhs + failedEquation b rhs ≤ 3 := by
130
+ rcases a with ⟨a₁, a₂, a₃⟩
131
+ rcases b with ⟨b₁, b₂, b₃⟩
132
+ cases a₁ <;> cases a₂ <;> cases a₃ <;>
133
+ cases b₁ <;> cases b₂ <;> cases b₃ <;> cases rhs <;> decide
134
+
135
+ theorem best_response_exact (b : Triple) (rhs : Bool) :
136
+ acceptedSlots (bestResponse b rhs) b rhs + failedEquation b rhs = 3 := by
137
+ rcases b with ⟨b₁, b₂, b₃⟩
138
+ cases b₁ <;> cases b₂ <;> cases b₃ <;> cases rhs <;> decide
139
+
140
+ structure Equation (Variable : Type u) where
141
+ first : Variable
142
+ second : Variable
143
+ third : Variable
144
+ rhs : Bool
145
+
146
+ inductive Slot where
147
+ | first
148
+ | second
149
+ | third
150
+ deriving DecidableEq
151
+
152
+ def nameAt (e : Equation Variable) : Slot → Variable
153
+ | .first => e.first
154
+ | .second => e.second
155
+ | .third => e.third
156
+
157
+ def bitAt (a : Triple) : Slot → Bool
158
+ | .first => a.first
159
+ | .second => a.second
160
+ | .third => a.third
161
+
162
+ def questionPredicate (e : Equation Variable) (name : Variable)
163
+ (alice : Triple) (bob : Bool) : Prop :=
164
+ parity alice = e.rhs ∧
165
+ ((e.first = name ∧ alice.first = bob) ∨
166
+ (e.second = name ∧ alice.second = bob) ∨
167
+ (e.third = name ∧ alice.third = bob))
168
+
169
+ theorem question_predicate_at_slot (e : Equation Variable)
170
+ (distinct₁₂ : e.first ≠ e.second) (distinct₁₃ : e.first ≠ e.third)
171
+ (distinct₂₃ : e.second ≠ e.third) (alice : Triple) (bob : Bool) (slot : Slot) :
172
+ questionPredicate e (nameAt e slot) alice bob ↔
173
+ parity alice = e.rhs ∧ bitAt alice slot = bob := by
174
+ cases slot <;>
175
+ simp [questionPredicate, nameAt, bitAt, distinct₁₂, distinct₁₃, distinct₂₃,
176
+ Ne.symm distinct₁₂, Ne.symm distinct₁₃, Ne.symm distinct₂₃]
177
+
178
+ def bobTriple (g : Variable → Bool) (e : Equation Variable) : Triple :=
179
+ ⟨g e.first, g e.second, g e.third⟩
180
+
181
+ def acceptedCount (equations : Index → Equation Variable)
182
+ (g : Variable → Bool) (alice : Index → Triple) : List Index → Nat
183
+ | [] => 0
184
+ | i :: rest =>
185
+ acceptedSlots (alice i) (bobTriple g (equations i)) (equations i).rhs +
186
+ acceptedCount equations g alice rest
187
+
188
+ def failureCount (equations : Index → Equation Variable)
189
+ (g : Variable → Bool) : List Index → Nat
190
+ | [] => 0
191
+ | i :: rest =>
192
+ failedEquation (bobTriple g (equations i)) (equations i).rhs +
193
+ failureCount equations g rest
194
+
195
+ theorem total_count_bound (equations : Index → Equation Variable)
196
+ (g : Variable → Bool) (alice : Index → Triple) (occurrences : List Index) :
197
+ acceptedCount equations g alice occurrences + failureCount equations g occurrences ≤
198
+ 3 * occurrences.length := by
199
+ induction occurrences with
200
+ | nil => simp [acceptedCount, failureCount]
201
+ | cons i rest ih =>
202
+ have h := local_count_bound (alice i) (bobTriple g (equations i)) (equations i).rhs
203
+ simp only [acceptedCount, failureCount, List.length_cons]
204
+ omega
205
+
206
+ def optimalAlice (equations : Index → Equation Variable) (g : Variable → Bool)
207
+ (i : Index) : Triple :=
208
+ bestResponse (bobTriple g (equations i)) (equations i).rhs
209
+
210
+ theorem optimal_alice_exact (equations : Index → Equation Variable)
211
+ (g : Variable → Bool) (occurrences : List Index) :
212
+ acceptedCount equations g (optimalAlice equations g) occurrences +
213
+ failureCount equations g occurrences = 3 * occurrences.length := by
214
+ induction occurrences with
215
+ | nil => simp [acceptedCount, failureCount]
216
+ | cons i rest ih =>
217
+ have h := best_response_exact (bobTriple g (equations i)) (equations i).rhs
218
+ simp only [acceptedCount, failureCount, List.length_cons, optimalAlice]
219
+ omega
220
+
221
+ theorem fixed_bob_optimum (equations : Index → Equation Variable)
222
+ (g : Variable → Bool) (occurrences : List Index) :
223
+ ∃ alice : Index → Triple,
224
+ acceptedCount equations g alice occurrences + failureCount equations g occurrences =
225
+ 3 * occurrences.length ∧
226
+ ∀ other : Index → Triple,
227
+ acceptedCount equations g other occurrences ≤
228
+ acceptedCount equations g alice occurrences := by
229
+ refine ⟨optimalAlice equations g, optimal_alice_exact equations g occurrences, ?_⟩
230
+ intro other
231
+ have h := total_count_bound equations g other occurrences
232
+ have heq := optimal_alice_exact equations g occurrences
233
+ omega
234
+
235
+ theorem soundness_191_over_192 (equations : Index → Equation Variable)
236
+ (g : Variable → Bool) (alice : Index → Triple) (occurrences : List Index)
237
+ (source_gap : occurrences.length ≤ 64 * failureCount equations g occurrences) :
238
+ 64 * acceptedCount equations g alice occurrences ≤ 191 * occurrences.length := by
239
+ have h := total_count_bound equations g alice occurrences
240
+ omega
241
+
242
+ theorem game_soundness_191_over_192 (equations : Index → Equation Variable)
243
+ (occurrences : List Index)
244
+ (source_gap : ∀ g : Variable → Bool,
245
+ occurrences.length ≤ 64 * failureCount equations g occurrences) :
246
+ ∀ (g : Variable → Bool) (alice : Index → Triple),
247
+ 64 * acceptedCount equations g alice occurrences ≤ 191 * occurrences.length := by
248
+ intro g alice
249
+ exact soundness_191_over_192 equations g alice occurrences (source_gap g)
250
+
251
+ end MinUncutGames.Reduction.Incidence
252
+
253
+ end
254
+ section
255
+ namespace MinUncutGames.Reduction.SourceIncidence
256
+
257
+ variable {Name : Type} {Index : Type*}
258
+
259
+ def toIncidence (e : CloneGap.Equation Name) : Incidence.Equation Name :=
260
+ ⟨e.first, e.second, e.third, e.rhs⟩
261
+
262
+ theorem failedEquation_eq (e : CloneGap.Equation Name) (g : Name → Bool) :
263
+ Incidence.failedEquation (Incidence.bobTriple g (toIncidence e)) (toIncidence e).rhs =
264
+ if CloneGap.satisfied e g then 0 else 1 := by
265
+ simp only [Incidence.failedEquation, Incidence.bobTriple, toIncidence,
266
+ Incidence.parity, CloneGap.satisfied]
267
+ simp
268
+
269
+ theorem failureCount_eq (equations : Index → CloneGap.Equation Name)
270
+ (g : Name → Bool) (occurrences : List Index) :
271
+ Incidence.failureCount (fun i => toIncidence (equations i)) g occurrences =
272
+ occurrences.countP (fun i => !CloneGap.satisfied (equations i) g) := by
273
+ induction occurrences with
274
+ | nil => rfl
275
+ | cons i rest ih =>
276
+ simp only [Incidence.failureCount, failedEquation_eq, ih, List.countP_cons]
277
+ cases CloneGap.satisfied (equations i) g <;> simp
278
+ omega
279
+
280
+ def occurrenceList (source : List (CloneGap.Equation Name)) :=
281
+ (CloneGap.cloneList source).zipIdx
282
+
283
+ theorem cloned_occurrence_gap (source : List (CloneGap.Equation Name))
284
+ (source_gap : ∀ A : Name → Bool,
285
+ source.length ≤ 4 * source.countP (fun e => !CloneGap.satisfied e A))
286
+ (g : Name × CloneGap.Index → Bool) :
287
+ (occurrenceList source).length ≤ 64 *
288
+ Incidence.failureCount (fun i => toIncidence i.1) g (occurrenceList source) := by
289
+ have hg := CloneGap.clone_gap source source_gap g
290
+ rw [failureCount_eq]
291
+ unfold occurrenceList
292
+ rw [List.length_zipIdx]
293
+ have hcount : ((CloneGap.cloneList source).zipIdx).countP
294
+ (fun i => !CloneGap.satisfied i.1 g) =
295
+ (CloneGap.cloneList source).countP (fun e => !CloneGap.satisfied e g) := by
296
+ have h := congrArg (fun es => es.countP (fun e => !CloneGap.satisfied e g))
297
+ (List.zipIdx_map_fst 0 (CloneGap.cloneList source))
298
+ simpa only [List.countP_map, Function.comp_def] using h
299
+ rw [hcount]
300
+ exact hg
301
+
302
+ theorem source_to_incidence_soundness (source : List (CloneGap.Equation Name))
303
+ (source_gap : ∀ A : Name → Bool,
304
+ source.length ≤ 4 * source.countP (fun e => !CloneGap.satisfied e A))
305
+ (g : Name × CloneGap.Index → Bool)
306
+ (alice : CloneGap.Equation (Name × CloneGap.Index) × Nat → Incidence.Triple) :
307
+ 64 * Incidence.acceptedCount (fun i => toIncidence i.1) g alice
308
+ (occurrenceList source) ≤ 191 * (occurrenceList source).length := by
309
+ exact Incidence.soundness_191_over_192 _ g alice _
310
+ (cloned_occurrence_gap source source_gap g)
311
+
312
+ end MinUncutGames.Reduction.SourceIncidence
313
+
314
+ end
315
+ section
316
+ namespace MinUncutGames.Reduction.FiniteSource
317
+
318
+ open CloneGap
319
+
320
+ variable {n : ℕ} {α β : Type*}
321
+
322
+ abbrev Name (s : ActualSource.Source) := Fin s.«variables» × Fin 48
323
+
324
+ def clonedSource (s : ActualSource.Source) := cloneList s.sourceList
325
+
326
+ abbrev Occurrence (s : ActualSource.Source) := Fin (clonedSource s).length
327
+
328
+ def occurrences (s : ActualSource.Source) : List (Occurrence s) :=
329
+ List.finRange (clonedSource s).length
330
+
331
+ def rawEquation (s : ActualSource.Source) (i : Occurrence s) : Equation (Fin s.«variables» × Nat) :=
332
+ (clonedSource s)[i.val]
333
+
334
+ def finiteName (s : ActualSource.Source) (v : Fin s.«variables» × Nat) : Name s :=
335
+ (v.1, ⟨v.2 % 48, Nat.mod_lt _ (by decide)⟩)
336
+
337
+ def mapEquation {α β : Type} (f : α → β) (e : Equation α) : Equation β :=
338
+ ⟨f e.first, f e.second, f e.third, e.rhs⟩
339
+
340
+ def equation (s : ActualSource.Source) (i : Occurrence s) : Equation (Name s) :=
341
+ mapEquation (finiteName s) (rawEquation s i)
342
+
343
+ theorem satisfied_map {α β : Type} (f : α → β) (e : Equation α) (g : β → Bool) :
344
+ satisfied (mapEquation f e) g = satisfied e (g ∘ f) := rfl
345
+
346
+ theorem mem_cart {xs : List α} {ys : List β} {z : α × β} :
347
+ z ∈ cart xs ys ↔ z.1 ∈ xs ∧ z.2 ∈ ys := by
348
+ simp only [cart, List.mem_flatMap, List.mem_map]
349
+ constructor
350
+ · rintro ⟨x, hx, y, hy, h⟩
351
+ cases h
352
+ exact ⟨hx, hy⟩
353
+ · rintro ⟨hx, hy⟩
354
+ exact ⟨z.1, hx, z.2, hy, rfl⟩
355
+
356
+ theorem distinctTriple_bounds {t : Nat × Nat × Nat} (h : t ∈ distinctTriples) :
357
+ t.1 < 48 ∧ t.2.1 < 48 ∧ t.2.2 < 48 := by
358
+ have h := (List.mem_filter.mp h).1
359
+ change t ∈ cart indices (cart indices indices) at h
360
+ rw [mem_cart, mem_cart] at h
361
+ simpa [indices] using h
362
+
363
+ theorem distinctTriples_nonempty : 0 < distinctTriples.length := by
364
+ have hm : (0, 1, 2) ∈ distinctTriples := by
365
+ simp [distinctTriples, triples, mem_cart, indices, collision]
366
+ exact List.length_pos_iff_exists_mem.mpr ⟨_, hm⟩
367
+
368
+ theorem cloned_member_properties {source : List (Equation (Fin n))}
369
+ {e : Equation (Fin n × Nat)} (h : e ∈ cloneList source) :
370
+ (e.first.2 < 48 ∧ e.second.2 < 48 ∧ e.third.2 < 48) ∧
371
+ (e.first ≠ e.second ∧ e.first ≠ e.third ∧ e.second ≠ e.third) := by
372
+ obtain ⟨old, _, h⟩ := List.mem_flatMap.mp h
373
+ obtain ⟨t, ht, rfl⟩ := List.mem_map.mp h
374
+ have hb := distinctTriple_bounds ht
375
+ have hc : collision t = false := by
376
+ simpa using (List.mem_filter.mp ht).2
377
+ exact ⟨hb, clone_names_distinct old t hc⟩
378
+
379
+ theorem raw_properties (s : ActualSource.Source) (i : Occurrence s) :
380
+ ((rawEquation s i).first.2 < 48 ∧ (rawEquation s i).second.2 < 48 ∧
381
+ (rawEquation s i).third.2 < 48) ∧
382
+ ((rawEquation s i).first ≠ (rawEquation s i).second ∧
383
+ (rawEquation s i).first ≠ (rawEquation s i).third ∧
384
+ (rawEquation s i).second ≠ (rawEquation s i).third) := by
385
+ apply cloned_member_properties
386
+ exact List.getElem_mem i.isLt
387
+
388
+ theorem finiteName_injective_on (s : ActualSource.Source)
389
+ {u v : Fin s.«variables» × Nat} (hu : u.2 < 48) (hv : v.2 < 48)
390
+ (h : finiteName s u = finiteName s v) : u = v := by
391
+ have he := congrArg (fun z : Name s => (z.1, z.2.val)) h
392
+ simpa [finiteName, Nat.mod_eq_of_lt hu, Nat.mod_eq_of_lt hv] using he
393
+
394
+ theorem names_distinct (s : ActualSource.Source) (i : Occurrence s) :
395
+ (equation s i).first ≠ (equation s i).second ∧
396
+ (equation s i).first ≠ (equation s i).third ∧
397
+ (equation s i).second ≠ (equation s i).third := by
398
+ obtain ⟨⟨h₁, h₂, h₃⟩, ⟨h₁₂, h₁₃, h₂₃⟩⟩ := raw_properties s i
399
+ exact ⟨fun h => h₁₂ (finiteName_injective_on s h₁ h₂ h),
400
+ fun h => h₁₃ (finiteName_injective_on s h₁ h₃ h),
401
+ fun h => h₂₃ (finiteName_injective_on s h₂ h₃ h)⟩
402
+
403
+ theorem raw_map_occurrences (s : ActualSource.Source) :
404
+ (occurrences s).map (rawEquation s) = clonedSource s := by
405
+ simp [occurrences, List.finRange, List.map_ofFn, rawEquation, Function.comp_def]
406
+
407
+ theorem occurrences_length (s : ActualSource.Source) :
408
+ (occurrences s).length = (clonedSource s).length := by
409
+ simp [occurrences]
410
+
411
+ theorem clonedSource_nonempty (s : ActualSource.Source) : 0 < (clonedSource s).length := by
412
+ rw [clonedSource, length_cloneList]
413
+ have hs : 0 < s.sourceList.length := by
414
+ simpa [ActualSource.Source.sourceList] using s.nonempty
415
+ exact Nat.mul_pos hs distinctTriples_nonempty
416
+
417
+ instance (s : ActualSource.Source) : Nonempty (Occurrence s) :=
418
+ ⟨⟨0, clonedSource_nonempty s⟩⟩
419
+
420
+ theorem indexed_failure_count (s : ActualSource.Source) (g : Name s → Bool) :
421
+ (occurrences s).countP (fun i => !satisfied (equation s i) g) =
422
+ (clonedSource s).countP (fun e => !satisfied e (g ∘ finiteName s)) := by
423
+ have h := congrArg (fun es => es.countP
424
+ (fun e => !satisfied e (g ∘ finiteName s))) (raw_map_occurrences s)
425
+ simpa only [List.countP_map, Function.comp_def, equation, satisfied_map] using h
426
+
427
+ theorem indexed_gap (s : ActualSource.Source)
428
+ (source_gap : ∀ A : Fin s.«variables» → Bool,
429
+ s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !satisfied e A))
430
+ (g : Name s → Bool) :
431
+ (occurrences s).length ≤
432
+ 64 * (occurrences s).countP (fun i => !satisfied (equation s i) g) := by
433
+ rw [occurrences_length, indexed_failure_count]
434
+ exact clone_gap s.sourceList source_gap (g ∘ finiteName s)
435
+
436
+ theorem indexed_completeness_count (s : ActualSource.Source) (A : Fin s.«variables» → Bool) :
437
+ (occurrences s).countP (fun i => satisfied (equation s i) (fun z => A z.1)) =
438
+ s.sourceList.countP (fun e => satisfied e A) * distinctTriples.length := by
439
+ have h := congrArg (fun es => es.countP
440
+ (fun e => satisfied e (fun z => A z.1))) (raw_map_occurrences s)
441
+ simp only [List.countP_map, Function.comp_def] at h
442
+ change (occurrences s).countP
443
+ (fun i => satisfied (rawEquation s i) (fun z => A z.1)) = _
444
+ rw [h]
445
+ exact clone_completeness_count s.sourceList A
446
+
447
+ def incidenceEquation (s : ActualSource.Source) (i : Occurrence s) :
448
+ Incidence.Equation (Name s) := SourceIncidence.toIncidence (equation s i)
449
+
450
+ theorem incidence_question_predicate (s : ActualSource.Source) (i : Occurrence s)
451
+ (alice : Incidence.Triple) (bob : Bool) (slot : Incidence.Slot) :
452
+ Incidence.questionPredicate (incidenceEquation s i)
453
+ (Incidence.nameAt (incidenceEquation s i) slot) alice bob ↔
454
+ Incidence.parity alice = (incidenceEquation s i).rhs ∧
455
+ Incidence.bitAt alice slot = bob := by
456
+ obtain ⟨h₁₂, h₁₃, h₂₃⟩ := names_distinct s i
457
+ exact Incidence.question_predicate_at_slot _ h₁₂ h₁₃ h₂₃ alice bob slot
458
+
459
+ theorem incidence_failure_gap (s : ActualSource.Source)
460
+ (source_gap : ∀ A : Fin s.«variables» → Bool,
461
+ s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !satisfied e A))
462
+ (g : Name s → Bool) :
463
+ (occurrences s).length ≤
464
+ 64 * Incidence.failureCount (incidenceEquation s) g (occurrences s) := by
465
+ unfold incidenceEquation
466
+ rw [SourceIncidence.failureCount_eq]
467
+ exact indexed_gap s source_gap g
468
+
469
+ theorem incidence_soundness (s : ActualSource.Source)
470
+ (source_gap : ∀ A : Fin s.«variables» → Bool,
471
+ s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !satisfied e A))
472
+ (g : Name s → Bool) (alice : Occurrence s → Incidence.Triple) :
473
+ 64 * Incidence.acceptedCount (incidenceEquation s) g alice (occurrences s) ≤
474
+ 191 * (occurrences s).length :=
475
+ Incidence.soundness_191_over_192 _ g alice _ (incidence_failure_gap s source_gap g)
476
+
477
+ def nameEquiv (s : ActualSource.Source) : Name s ≃ Fin (s.«variables» * 48) :=
478
+ finProdFinEquiv
479
+
480
+ def cloned (s : ActualSource.Source) : ActualSource.Source where
481
+ «variables» := s.«variables» * 48
482
+ occurrences := (clonedSource s).length
483
+ nonempty := clonedSource_nonempty s
484
+ equation i := mapEquation (nameEquiv s) (equation s i)
485
+
486
+ theorem cloned_length (s : ActualSource.Source) :
487
+ (cloned s).occurrences = s.occurrences * distinctTriples.length := by
488
+ change (cloneList s.sourceList).length = _
489
+ rw [length_cloneList, ActualSource.Source.sourceList_length]
490
+
491
+ theorem cloned_distinct (s : ActualSource.Source) : (cloned s).DistinctNames := by
492
+ intro i
493
+ obtain ⟨h₁₂, h₁₃, h₂₃⟩ := names_distinct s i
494
+ exact ⟨fun h => h₁₂ ((nameEquiv s).injective h),
495
+ fun h => h₁₃ ((nameEquiv s).injective h),
496
+ fun h => h₂₃ ((nameEquiv s).injective h)⟩
497
+
498
+ theorem count_ofFn (f : Fin n → α) (p : α → Bool) :
499
+ (List.ofFn f).countP p = (List.finRange n).countP (fun i => p (f i)) := by
500
+ have he : (List.finRange n).map f = List.ofFn f := by
501
+ simp [List.finRange, List.map_ofFn, Function.comp_def]
502
+ have h := congrArg (fun es => es.countP p) he
503
+ simpa only [List.countP_map, Function.comp_def] using h.symm
504
+
505
+ theorem cloned_gap (s : ActualSource.Source)
506
+ (source_gap : ∀ A : Fin s.«variables» → Bool,
507
+ s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !satisfied e A))
508
+ (A : Fin (cloned s).«variables» → Bool) :
509
+ (cloned s).sourceList.length ≤
510
+ 64 * (cloned s).sourceList.countP (fun e => !satisfied e A) := by
511
+ change Fin (s.«variables» * 48) → Bool at A
512
+ have h := indexed_gap s source_gap (A ∘ nameEquiv s)
513
+ rw [occurrences_length] at h
514
+ change (List.ofFn (fun i => mapEquation (nameEquiv s) (equation s i))).length ≤
515
+ 64 * (List.ofFn (fun i => mapEquation (nameEquiv s) (equation s i))).countP
516
+ (fun e => !satisfied e A)
517
+ rw [List.length_ofFn, count_ofFn]
518
+ exact h
519
+
520
+ theorem cloned_completeness_count (s : ActualSource.Source) (A : Fin s.«variables» → Bool) :
521
+ (cloned s).sourceList.countP
522
+ (fun e => satisfied e (fun z => A ((nameEquiv s).symm z).1)) =
523
+ s.sourceList.countP (fun e => satisfied e A) * distinctTriples.length := by
524
+ have h := indexed_completeness_count s A
525
+ simpa only [ActualSource.Source.sourceList, count_ofFn, cloned, satisfied_map,
526
+ Function.comp_def, Equiv.symm_apply_apply, occurrences] using h
527
+
528
+ end MinUncutGames.Reduction.FiniteSource
529
+
530
+ end
531
+ section
532
+ namespace MinUncutGames.Soundness.IncidenceExtraction
533
+
534
+ abbrev Triple := Fin 3 → Bool
535
+
536
+ def xorTriple (x : Triple) : Bool := (x 0 ^^ x 1) ^^ x 2
537
+
538
+ structure Incidence (Occurrence Name : Type) where
539
+ name : Occurrence → Fin 3 → Name
540
+ rhs : Occurrence → Bool
541
+
542
+ def Incidence.accepts {Occurrence Name : Type}
543
+ (g : Incidence Occurrence Name) (o : Occurrence) (i : Fin 3)
544
+ (a : Triple) (b : Bool) : Prop :=
545
+ xorTriple a = g.rhs o ∧ a i = b
546
+
547
+ def Incidence.namedAccepts {Occurrence Name : Type}
548
+ (g : Incidence Occurrence Name) (o : Occurrence) (n : Name)
549
+ (a : Triple) (b : Bool) : Prop :=
550
+ ∃ i, g.name o i = n ∧ g.accepts o i a b
551
+
552
+ theorem Incidence.accepts_implies_namedAccepts {Occurrence Name : Type}
553
+ (g : Incidence Occurrence Name) (o : Occurrence) (i : Fin 3)
554
+ (a : Triple) (b : Bool) (h : g.accepts o i a b) :
555
+ g.namedAccepts o (g.name o i) a b :=
556
+ ⟨i, rfl, h⟩
557
+
558
+ theorem Incidence.namedAccepts_iff_accepts {Occurrence Name : Type}
559
+ (g : Incidence Occurrence Name)
560
+ (distinct : ∀ o i j, g.name o i = g.name o j → i = j)
561
+ (o : Occurrence) (i : Fin 3) (a : Triple) (b : Bool) :
562
+ g.namedAccepts o (g.name o i) a b ↔ g.accepts o i a b := by
563
+ constructor
564
+ · rintro ⟨j, hname, h⟩
565
+ have hji := distinct o j i hname
566
+ simpa [hji] using h
567
+ · exact g.accepts_implies_namedAccepts o i a b
568
+
569
+ structure FullPoint (Position : Type) where
570
+ homogeneous : Bool
571
+ coords : Position → Triple
572
+
573
+ def FullPoint.valid {Position Occurrence Name : Type}
574
+ (g : Incidence Occurrence Name) (u : Position → Occurrence)
575
+ (e : FullPoint Position) : Prop :=
576
+ ∀ j, xorTriple (e.coords j) = (g.rhs (u j) && e.homogeneous)
577
+
578
+ structure PartnerPoint (Position : Type) where
579
+ homogeneous : Bool
580
+ single : Position → Bool
581
+
582
+ def AugmentedAccepts {Position Occurrence Name : Type}
583
+ (g : Incidence Occurrence Name) (u : Position → Occurrence)
584
+ (active : Position → Prop) (slot : Position → Fin 3)
585
+ (eA : FullPoint Position) (eB : PartnerPoint Position) : Prop :=
586
+ eA.valid g u ∧ eA.homogeneous = true ∧ eB.homogeneous = true ∧
587
+ ∀ j, active j → eA.coords j (slot j) = eB.single j
588
+
589
+ def RepeatedAccepts {Position Occurrence Name : Type}
590
+ (g : Incidence Occurrence Name) (u : Position → Occurrence)
591
+ (slot : Position → Fin 3) (inside : Position → Prop)
592
+ (answerA : Position → Triple) (answerB : Position → Bool) : Prop :=
593
+ ∀ j, inside j → g.accepts (u j) (slot j) (answerA j) (answerB j)
594
+
595
+ theorem augmented_accepts_implies_repeated_accepts
596
+ {Position Occurrence Name : Type}
597
+ (g : Incidence Occurrence Name) (u : Position → Occurrence)
598
+ (active inside : Position → Prop) (slot : Position → Fin 3)
599
+ (eA : FullPoint Position) (eB : PartnerPoint Position)
600
+ (hinside : ∀ j, inside j → active j)
601
+ (haccept : AugmentedAccepts g u active slot eA eB) :
602
+ RepeatedAccepts g u slot inside eA.coords eB.single := by
603
+ obtain ⟨hvalid, hone, _, hagree⟩ := haccept
604
+ intro j hj
605
+ constructor
606
+ · have heq := hvalid j
607
+ simpa [hone] using heq
608
+ · exact hagree j (hinside j hj)
609
+
610
+ theorem augmented_accepts_implies_named_repeated_accepts
611
+ {Position RepeatPosition Occurrence Name : Type}
612
+ (g : Incidence Occurrence Name) (u : Position → Occurrence)
613
+ (active : Position → Prop) (slot : Position → Fin 3)
614
+ (embed : RepeatPosition → Position)
615
+ (eA : FullPoint Position) (eB : PartnerPoint Position)
616
+ (hinside : ∀ r, active (embed r))
617
+ (haccept : AugmentedAccepts g u active slot eA eB) :
618
+ ∀ r, g.namedAccepts (u (embed r))
619
+ (g.name (u (embed r)) (slot (embed r)))
620
+ (eA.coords (embed r)) (eB.single (embed r)) := by
621
+ intro r
622
+ apply g.accepts_implies_namedAccepts
623
+ obtain ⟨hvalid, hone, _, hagree⟩ := haccept
624
+ constructor
625
+ · have heq := hvalid (embed r)
626
+ simpa [hone] using heq
627
+ · exact hagree (embed r) (hinside r)
628
+
629
+ structure Game (QA QB A B : Type) where
630
+ accepts : QA → QB → A → B → Prop
631
+
632
+ structure Strategies (QA QB A B : Type) where
633
+ first : QA → A
634
+ second : QB → B
635
+
636
+ def Strategies.wins {QA QB A B : Type} (s : Strategies QA QB A B)
637
+ (g : Game QA QB A B) (qa : QA) (qb : QB) : Prop :=
638
+ g.accepts qa qb (s.first qa) (s.second qb)
639
+
640
+ structure LocalSimulation
641
+ {InnerQA InnerQB InnerA InnerB OuterQA OuterQB OuterA OuterB : Type}
642
+ (inner : Game InnerQA InnerQB InnerA InnerB)
643
+ (outer : Game OuterQA OuterQB OuterA OuterB) where
644
+ questionA : InnerQA → OuterQA
645
+ questionB : InnerQB → OuterQB
646
+ answerA : InnerQA → OuterA → InnerA
647
+ answerB : InnerQB → OuterB → InnerB
648
+ sound : ∀ qa qb a b,
649
+ outer.accepts (questionA qa) (questionB qb) a b →
650
+ inner.accepts qa qb (answerA qa a) (answerB qb b)
651
+
652
+ def LocalSimulation.induced
653
+ {InnerQA InnerQB InnerA InnerB OuterQA OuterQB OuterA OuterB : Type}
654
+ {inner : Game InnerQA InnerQB InnerA InnerB}
655
+ {outer : Game OuterQA OuterQB OuterA OuterB}
656
+ (r : LocalSimulation inner outer)
657
+ (s : Strategies OuterQA OuterQB OuterA OuterB) :
658
+ Strategies InnerQA InnerQB InnerA InnerB where
659
+ first qa := r.answerA qa (s.first (r.questionA qa))
660
+ second qb := r.answerB qb (s.second (r.questionB qb))
661
+
662
+ theorem LocalSimulation.induced_wins
663
+ {InnerQA InnerQB InnerA InnerB OuterQA OuterQB OuterA OuterB : Type}
664
+ {inner : Game InnerQA InnerQB InnerA InnerB}
665
+ {outer : Game OuterQA OuterQB OuterA OuterB}
666
+ (r : LocalSimulation inner outer)
667
+ (s : Strategies OuterQA OuterQB OuterA OuterB)
668
+ (qa : InnerQA) (qb : InnerQB)
669
+ (hwins : s.wins outer (r.questionA qa) (r.questionB qb)) :
670
+ (r.induced s).wins inner qa qb :=
671
+ r.sound qa qb (s.first (r.questionA qa)) (s.second (r.questionB qb)) hwins
672
+
673
+ theorem LocalSimulation.seeded_induced_wins
674
+ {InnerQA InnerQB InnerA InnerB OuterQA OuterQB OuterA OuterB Seed : Type}
675
+ {inner : Game InnerQA InnerQB InnerA InnerB}
676
+ {outer : Game OuterQA OuterQB OuterA OuterB}
677
+ (r : LocalSimulation inner outer)
678
+ (strategy : Seed → Strategies OuterQA OuterQB OuterA OuterB)
679
+ (seed : Seed) (qa : InnerQA) (qb : InnerQB)
680
+ (hwins : (strategy seed).wins outer (r.questionA qa) (r.questionB qb)) :
681
+ (r.induced (strategy seed)).wins inner qa qb :=
682
+ r.induced_wins (strategy seed) qa qb hwins
683
+
684
+ end MinUncutGames.Soundness.IncidenceExtraction
685
+
686
+ end
687
+
688
+ end OAI
lean/OAI/Computability/MinUncut/Games/AdaptiveKernel.lean ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.TripleKernel
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ noncomputable section
8
+ open scoped BigOperators
9
+ namespace MinUncut.Composition
10
+ open BinaryFourier OuterSmoothness
11
+ attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype
12
+
13
+ abbrev TripleIndex (J : Type*) := Option (Option (Option J))
14
+
15
+ def tripleTupleEquiv {J A : Type*} :
16
+ (TripleIndex J → A) ≃ ((J → A) × (A × A × A)) where
17
+ toFun L := (fun j => L (some (some (some j))), L none,L (some none),L (some (some none)))
18
+ invFun z
19
+ | none => z.2.1
20
+ | some none => z.2.2.1
21
+ | some (some none) => z.2.2.2
22
+ | some (some (some j)) => z.1 j
23
+ left_inv L := by funext j; cases j with
24
+ | none => rfl
25
+ | some j => cases j with
26
+ | none => rfl
27
+ | some j => cases j <;> rfl
28
+ right_inv _ := rfl
29
+
30
+ lemma TripleIndex.card (J : Type*) [Fintype J] :
31
+ Fintype.card (TripleIndex J)=Fintype.card J+3 := by simp [TripleIndex]
32
+
33
+ variable {J V W : Type*} [Fintype J] [DecidableEq J]
34
+ [AddCommGroup V] [Module F₂ V] [Fintype V]
35
+ [AddCommGroup W] [Module F₂ W] [Fintype W]
36
+
37
+ def adaptiveKernel (f : (J → V) → V → ℝ) (u : ℝ) (L : TripleIndex J → V) : ℝ :=
38
+ tripleKernel (remainder (f (tripleTupleEquiv L).1) u) (tripleTupleEquiv L).2
39
+
40
+ omit [Fintype J] [DecidableEq J] in
41
+ lemma adaptiveKernel_abs (f : (J → V) → V → ℝ) {M u : ℝ}
42
+ (hM : 0≤M) (hu : 0<u) (hf : ∀ D z, |f D z|≤M) (L : TripleIndex J → V) :
43
+ |adaptiveKernel f u L|≤(M+M^2/u)^4 :=
44
+ tripleKernel_abs _ (by positivity) (remainder_abs_bound _ hM hu (hf _)) _
45
+
46
+ lemma adaptiveKernel_uniform (f : (J → V) → V → ℝ) {M u : ℝ}
47
+ (hM : 0≤M) (hu : 0<u) (hf : ∀ D z, |f D z|≤M) :
48
+ (𝔼 L : TripleIndex J → V, adaptiveKernel f u L)≤u^2*M^2 := by
49
+ have he : (𝔼 L : TripleIndex J → V, adaptiveKernel f u L) =
50
+ 𝔼 z : (J → V) × (V × V × V), tripleKernel (remainder (f z.1) u) z.2 :=
51
+ Fintype.expect_equiv tripleTupleEquiv _ _ (fun _ => rfl)
52
+ rw [he,expect_pair]
53
+ simp_rw [tripleKernel_mean]
54
+ exact (Finset.expect_le_expect (fun D _ => remainder_fourth_bound (f D) hM hu (hf D))).trans_eq
55
+ (Fintype.expect_const _)
56
+
57
+ omit [Fintype J] [DecidableEq J] [Fintype W] in
58
+ lemma adaptiveKernel_pullback (π : W →ₗ[F₂] V) (f : (J → V) → V → ℝ) (u : ℝ)
59
+ (L : TripleIndex J → W) :
60
+ adaptiveKernel f u (fun j => π (L j)) =
61
+ tripleKernel (fun z => remainder (f (fun j => π ((tripleTupleEquiv L).1 j))) u (π z))
62
+ (tripleTupleEquiv L).2 := by
63
+ simp only [adaptiveKernel,tripleKernel,tripleTupleEquiv,Equiv.coe_fn_mk,map_add]
64
+
65
+ lemma adaptiveKernel_pullback_mean (π : W →ₗ[F₂] V) (f : (J → V) → V → ℝ) (u : ℝ) :
66
+ (𝔼 L : TripleIndex J → W, adaptiveKernel f u (fun j => π (L j))) =
67
+ 𝔼 D : J → W, ∑ β : Module.Dual F₂ W,
68
+ coefficient (fun z => remainder (f (fun j => π (D j))) u (π z)) β ^4 := by
69
+ simp_rw [adaptiveKernel_pullback]
70
+ have he := Fintype.expect_equiv (tripleTupleEquiv (J := J) (A := W))
71
+ (fun L => tripleKernel (fun z => remainder (f (fun j => π ((tripleTupleEquiv L).1 j))) u (π z))
72
+ (tripleTupleEquiv L).2)
73
+ (fun z => tripleKernel (fun w => remainder (f (fun j => π (z.1 j))) u (π w)) z.2)
74
+ (fun _ => rfl)
75
+ rw [he,expect_pair]
76
+ simp_rw [tripleKernel_mean]
77
+
78
+ end MinUncut.Composition
79
+
80
+ end
81
+ end
82
+
83
+ end OAI
lean/OAI/Computability/MinUncut/Games/AffineLabels.lean ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.F2
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ noncomputable section
8
+ namespace MinUncut.Inner
9
+ open BinaryFourier
10
+ variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A]
11
+
12
+ def labelFrequency (a : A) : Module.Dual F₂ (Forms A) where
13
+ toFun b := b a
14
+ map_add' _ _ := rfl
15
+ map_smul' _ _ := rfl
16
+
17
+ @[simp] lemma labelFrequency_apply (a : A) (b : Forms A) : labelFrequency a b = b a := rfl
18
+ @[simp] lemma labelFrequency_odd (a : A) :
19
+ labelFrequency a (AffineMap.const F₂ A 1) = 1 := rfl
20
+
21
+ def basedForm (a₀ : A) : Module.Dual F₂ V →ₗ[F₂] Forms A where
22
+ toFun l := l.toAffineMap.comp (AffineEquiv.vaddConst F₂ a₀).symm.toAffineMap
23
+ map_add' l k := by ext a; rfl
24
+ map_smul' t l := by ext a; rfl
25
+
26
+ @[simp] lemma basedForm_apply (a₀ a : A) (l : Module.Dual F₂ V) :
27
+ basedForm a₀ l a = l (a -ᵥ a₀) := rfl
28
+
29
+ lemma form_decomposition (a₀ : A) (b : Forms A) :
30
+ b = basedForm a₀ b.linear + b a₀ • AffineMap.const F₂ A 1 := by
31
+ ext a
32
+ have h := b.map_vadd a₀ (a -ᵥ a₀)
33
+ simpa only [vsub_vadd, vadd_eq_add, AffineMap.coe_add, AffineMap.coe_smul, Pi.add_apply, Pi.smul_apply,
34
+ AffineMap.const_apply, smul_eq_mul, mul_one, basedForm_apply] using h
35
+
36
+ lemma labelFrequency_injective : Function.Injective (labelFrequency (A := A)) := by
37
+ intro a a' h
38
+ have hlin : (Module.Dual.eval F₂ V) (a -ᵥ a') = 0 := by
39
+ ext l
40
+ have hh := congrArg (fun α : Module.Dual F₂ (Forms A) => α (basedForm a' l)) h
41
+ simpa using hh
42
+ have hz : a -ᵥ a' = 0 := (Module.eval_apply_eq_zero_iff F₂ _).mp hlin
43
+ exact vsub_eq_zero_iff_eq.mp hz
44
+
45
+ variable [Fintype A]
46
+
47
+ lemma oddFrequency_exists_label (α : Module.Dual F₂ (Forms A))
48
+ (hα : α (AffineMap.const F₂ A 1) = 1) : ∃ a : A, labelFrequency a = α := by
49
+ let a₀ : A := Classical.choice (inferInstance : Nonempty A)
50
+ let : Fintype V := Fintype.ofEquiv A (AffineEquiv.vaddConst F₂ a₀).toEquiv.symm
51
+ obtain ⟨v,hv⟩ := (Module.bijective_dual_eval F₂ V).2 (α.comp (basedForm a₀))
52
+ refine ⟨v +ᵥ a₀, ?_⟩
53
+ apply LinearMap.ext
54
+ intro b
55
+ have hb : α b = b.linear v + b a₀ := by
56
+ conv_lhs => rw [form_decomposition a₀ b]
57
+ rw [map_add, map_smul, hα]
58
+ have hh := congrArg (fun β : Module.Dual F₂ (Module.Dual F₂ V) => β b.linear) hv
59
+ change b.linear v = α (basedForm a₀ b.linear) at hh
60
+ rw [← hh]
61
+ simp
62
+ simpa only [labelFrequency_apply, AffineMap.map_vadd, vadd_eq_add] using hb.symm
63
+
64
+ def oddFrequencyEquiv : A ≃ {α : Module.Dual F₂ (Forms A) //
65
+ α (AffineMap.const F₂ A 1) = 1} :=
66
+ Equiv.ofBijective (fun a => ⟨labelFrequency a, labelFrequency_odd a⟩)
67
+ ⟨fun _ _ h => labelFrequency_injective (congrArg Subtype.val h),
68
+ fun α => by
69
+ obtain ⟨a,ha⟩ := oddFrequency_exists_label α.val α.property
70
+ exact ⟨a, Subtype.ext ha⟩⟩
71
+
72
+ variable {V' A' : Type*} [AddCommGroup V'] [Module F₂ V'] [AddTorsor V' A']
73
+
74
+ def formPullback (π : A →ᵃ[F₂] A') : Forms A' →ₗ[F₂] Forms A where
75
+ toFun b := b.comp π
76
+ map_add' _ _ := by ext a; rfl
77
+ map_smul' _ _ := by ext a; rfl
78
+
79
+ omit [Fintype A] in
80
+ @[simp] lemma formPullback_one (π : A →ᵃ[F₂] A') :
81
+ formPullback π (AffineMap.const F₂ A' 1) = AffineMap.const F₂ A 1 := by ext a; rfl
82
+
83
+ omit [Fintype A] in
84
+ @[simp] lemma labelFrequency_pullback (π : A →ᵃ[F₂] A') (a : A) :
85
+ (labelFrequency a).comp (formPullback π) = labelFrequency (π a) := rfl
86
+ end MinUncut.Inner
87
+
88
+ end
89
+ end
90
+
91
+ end OAI
lean/OAI/Computability/MinUncut/Games/Basic.lean ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.OuterQuestions
3
+
4
+ namespace OAI
5
+
6
+ namespace MinUncutGames.Foundations.CorrelatedSampling
7
+
8
+ def firstAccepted {σ : Type*} (accept : σ → Bool) : List σ → Option σ
9
+ | [] => none
10
+ | proposal :: rest =>
11
+ if accept proposal then some proposal else firstAccepted accept rest
12
+
13
+ theorem first_union_common {σ : Type*} (left right : σ → Bool)
14
+ (proposals : List σ) (proposal : σ)
15
+ (hfirst : firstAccepted (fun s => left s || right s) proposals = some proposal)
16
+ (hleft : left proposal = true) (hright : right proposal = true) :
17
+ firstAccepted left proposals = some proposal ∧
18
+ firstAccepted right proposals = some proposal := by
19
+ induction proposals with
20
+ | nil => simp [firstAccepted] at hfirst
21
+ | cons head tail ih =>
22
+ by_cases hl : left head = true
23
+ · have heq : head = proposal := by
24
+ simpa [firstAccepted, hl] using hfirst
25
+ subst head
26
+ simp [firstAccepted, hleft, hright]
27
+ · by_cases hr : right head = true
28
+ · have heq : head = proposal := by
29
+ simpa [firstAccepted, hl, hr] using hfirst
30
+ subst head
31
+ exact False.elim (hl hleft)
32
+ · have htail : firstAccepted (fun s => left s || right s) tail = some proposal := by
33
+ simpa [firstAccepted, hl, hr] using hfirst
34
+ simpa [firstAccepted, hl, hr] using ih htail
35
+
36
+ def thresholdSample {α : Type*} (mass : α → Nat) (proposals : List (α × Nat)) :
37
+ Option α :=
38
+ (firstAccepted (fun s => decide (s.2 < mass s.1)) proposals).map Prod.fst
39
+
40
+ theorem thresholdSample_agreement {α : Type*} (left right : α → Nat)
41
+ (proposals : List (α × Nat)) (a : α) (height : Nat)
42
+ (hfirst : firstAccepted
43
+ (fun s => decide (s.2 < left s.1) || decide (s.2 < right s.1)) proposals =
44
+ some (a, height))
45
+ (hcommon : height < min (left a) (right a)) :
46
+ thresholdSample left proposals = some a ∧
47
+ thresholdSample right proposals = some a := by
48
+ have h := first_union_common
49
+ (fun s : α × Nat => decide (s.2 < left s.1))
50
+ (fun s : α × Nat => decide (s.2 < right s.1)) proposals (a, height) hfirst
51
+ (by simpa using (lt_min_iff.mp hcommon).1)
52
+ (by simpa using (lt_min_iff.mp hcommon).2)
53
+ simp [thresholdSample, h.1, h.2]
54
+
55
+ noncomputable section
56
+
57
+ variable {α : Type*} [Fintype α]
58
+
59
+ def totalVariation (p q : α → ℝ) : ℝ := (∑ a, |p a - q a|) / 2
60
+
61
+ def overlapMass (p q : α → ℝ) : ℝ := ∑ a, min (p a) (q a)
62
+
63
+ def unionMass (p q : α → ℝ) : ℝ := ∑ a, max (p a) (q a)
64
+
65
+ theorem totalVariation_nonneg (p q : α → ℝ) : 0 ≤ totalVariation p q := by
66
+ unfold totalVariation
67
+ exact div_nonneg (Finset.sum_nonneg (fun _ _ => abs_nonneg _)) (by norm_num)
68
+
69
+ theorem overlapMass_nonneg (p q : α → ℝ) (hp : ∀ a, 0 ≤ p a)
70
+ (hq : ∀ a, 0 ≤ q a) : 0 ≤ overlapMass p q := by
71
+ exact Finset.sum_nonneg (fun a _ => le_min (hp a) (hq a))
72
+
73
+ private theorem min_abs_identity (x y : ℝ) : 2 * min x y + |x - y| = x + y := by
74
+ rcases le_total x y with h | h
75
+ · rw [min_eq_left h, abs_of_nonpos (sub_nonpos.mpr h)]
76
+ ring
77
+ · rw [min_eq_right h, abs_of_nonneg (sub_nonneg.mpr h)]
78
+ ring
79
+
80
+ private theorem max_abs_identity (x y : ℝ) : 2 * max x y - |x - y| = x + y := by
81
+ rcases le_total x y with h | h
82
+ · rw [max_eq_right h, abs_of_nonpos (sub_nonpos.mpr h)]
83
+ ring
84
+ · rw [max_eq_left h, abs_of_nonneg (sub_nonneg.mpr h)]
85
+ ring
86
+
87
+ theorem overlapMass_eq (p q : α → ℝ) (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) :
88
+ overlapMass p q = 1 - totalVariation p q := by
89
+ have h := Finset.sum_congr (s₁ := Finset.univ) (s₂ := Finset.univ) rfl
90
+ (fun a _ => min_abs_identity (p a) (q a))
91
+ simp only [Finset.sum_add_distrib, ← Finset.mul_sum, hp, hq] at h
92
+ unfold overlapMass totalVariation
93
+ linarith
94
+
95
+ theorem unionMass_eq (p q : α → ℝ) (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) :
96
+ unionMass p q = 1 + totalVariation p q := by
97
+ have h := Finset.sum_congr (s₁ := Finset.univ) (s₂ := Finset.univ) rfl
98
+ (fun a _ => max_abs_identity (p a) (q a))
99
+ simp only [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, hp, hq] at h
100
+ unfold unionMass totalVariation
101
+ linarith
102
+
103
+ theorem totalVariation_le_one (p q : α → ℝ) (hp : ∀ a, 0 ≤ p a)
104
+ (hq : ∀ a, 0 ≤ q a) (hpsum : ∑ a, p a = 1) (hqsum : ∑ a, q a = 1) :
105
+ totalVariation p q ≤ 1 := by
106
+ have h := overlapMass_nonneg p q hp hq
107
+ rw [overlapMass_eq p q hpsum hqsum] at h
108
+ linarith
109
+
110
+ theorem overlap_union_ratio (p q : α → ℝ)
111
+ (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) :
112
+ overlapMass p q / unionMass p q =
113
+ (1 - totalVariation p q) / (1 + totalVariation p q) := by
114
+ rw [overlapMass_eq p q hp hq, unionMass_eq p q hp hq]
115
+
116
+ theorem overlap_union_ratio_lower_bound (p q : α → ℝ)
117
+ (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) :
118
+ 1 - 2 * totalVariation p q ≤ overlapMass p q / unionMass p q := by
119
+ rw [overlap_union_ratio p q hp hq]
120
+ have htv := totalVariation_nonneg p q
121
+ have hden : 0 < 1 + totalVariation p q := by linarith
122
+ apply (le_div_iff₀ hden).2
123
+ nlinarith [sq_nonneg (totalVariation p q)]
124
+
125
+ theorem first_union_disagreement_upper_bound (p q : α → ℝ)
126
+ (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) :
127
+ 1 - overlapMass p q / unionMass p q ≤ 2 * totalVariation p q := by
128
+ linarith [overlap_union_ratio_lower_bound p q hp hq]
129
+
130
+ variable {σ : Type*} [Fintype σ]
131
+
132
+ def eventMass (w : σ → ℝ) (event : σ → Bool) : ℝ :=
133
+ ∑ s, if event s then w s else 0
134
+
135
+ theorem eventMass_nonneg (w : σ → ℝ) (event : σ → Bool) (hw : ∀ s, 0 ≤ w s) :
136
+ 0 ≤ eventMass w event := by
137
+ apply Finset.sum_nonneg
138
+ intro s _
139
+ split <;> simp_all
140
+
141
+ theorem eventMass_complement (w : σ → ℝ) (event : σ → Bool)
142
+ (hw : ∑ s, w s = 1) :
143
+ eventMass w event + eventMass w (fun s => !(event s)) = 1 := by
144
+ unfold eventMass
145
+ rw [← Finset.sum_add_distrib]
146
+ calc
147
+ ∑ s, ((if event s then w s else 0) + (if !event s then w s else 0)) = ∑ s, w s := by
148
+ apply Finset.sum_congr rfl
149
+ intro s _
150
+ cases event s <;> simp
151
+ _ = 1 := hw
152
+
153
+ def geometricMass (r : ℝ) : Nat → ℝ
154
+ | 0 => 0
155
+ | n + 1 => 1 + r * geometricMass r n
156
+
157
+ theorem geometricMass_nonneg (r : ℝ) (hr : 0 ≤ r) (n : Nat) :
158
+ 0 ≤ geometricMass r n := by
159
+ induction n with
160
+ | zero => simp [geometricMass]
161
+ | succ n ih => exact add_nonneg (by norm_num) (mul_nonneg hr ih)
162
+
163
+ theorem geometricMass_identity (r : ℝ) (n : Nat) :
164
+ (1 - r) * geometricMass r n = 1 - r ^ n := by
165
+ induction n with
166
+ | zero => simp [geometricMass]
167
+ | succ n ih =>
168
+ simp only [geometricMass, pow_succ]
169
+ calc
170
+ (1 - r) * (1 + r * geometricMass r n) =
171
+ (1 - r) + r * ((1 - r) * geometricMass r n) := by ring
172
+ _ = 1 - r ^ n * r := by rw [ih]; ring
173
+
174
+ def firstHitWeight (w : σ → ℝ) (accept : σ → Bool) : Nat → Option σ → ℝ
175
+ | 0, none => 1
176
+ | 0, some _ => 0
177
+ | n + 1, none => eventMass w (fun s => !(accept s)) * firstHitWeight w accept n none
178
+ | n + 1, some s =>
179
+ (if accept s then w s else 0) +
180
+ eventMass w (fun s => !(accept s)) * firstHitWeight w accept n (some s)
181
+
182
+ theorem firstHitWeight_nonneg (w : σ → ℝ) (accept : σ → Bool)
183
+ (hw : ∀ s, 0 ≤ w s) (n : Nat) (output : Option σ) :
184
+ 0 ≤ firstHitWeight w accept n output := by
185
+ induction n generalizing output with
186
+ | zero => cases output <;> simp [firstHitWeight]
187
+ | succ n ih =>
188
+ have hr := eventMass_nonneg w (fun s => !(accept s)) hw
189
+ cases output with
190
+ | none => exact mul_nonneg hr (ih none)
191
+ | some s =>
192
+ apply add_nonneg
193
+ · split <;> simp_all
194
+ · exact mul_nonneg hr (ih (some s))
195
+
196
+ theorem firstHitWeight_none (w : σ → ℝ) (accept : σ → Bool) (n : Nat) :
197
+ firstHitWeight w accept n none = eventMass w (fun s => !(accept s)) ^ n := by
198
+ induction n with
199
+ | zero => simp [firstHitWeight]
200
+ | succ n ih => simp [firstHitWeight, ih, pow_succ, mul_comm]
201
+
202
+ theorem firstHitWeight_some (w : σ → ℝ) (accept : σ → Bool) (n : Nat) (s : σ) :
203
+ firstHitWeight w accept n (some s) =
204
+ (if accept s then w s else 0) *
205
+ geometricMass (eventMass w (fun s => !(accept s))) n := by
206
+ induction n with
207
+ | zero => simp [firstHitWeight, geometricMass]
208
+ | succ n ih =>
209
+ rw [firstHitWeight, geometricMass, ih]
210
+ ring
211
+
212
+ theorem firstHitWeight_normalized (w : σ → ℝ) (accept : σ → Bool)
213
+ (hw : ∑ s, w s = 1) (n : Nat) : ∑ output, firstHitWeight w accept n output = 1 := by
214
+ rw [Fintype.sum_option, firstHitWeight_none]
215
+ simp_rw [firstHitWeight_some]
216
+ rw [← Finset.sum_mul]
217
+ change eventMass w (fun s => !(accept s)) ^ n +
218
+ eventMass w accept * geometricMass (eventMass w (fun s => !(accept s))) n = 1
219
+ have hc := eventMass_complement w accept hw
220
+ have hg := geometricMass_identity (eventMass w (fun s => !(accept s))) n
221
+ have ha : eventMass w accept = 1 - eventMass w (fun s => !(accept s)) := by linarith
222
+ rw [ha, hg]
223
+ ring
224
+
225
+ def goodFirstMass (w : σ → ℝ) (accept good : σ → Bool) (n : Nat) : ℝ :=
226
+ ∑ s, if good s then firstHitWeight w accept n (some s) else 0
227
+
228
+ theorem goodFirstMass_eq (w : σ → ℝ) (accept good : σ → Bool) (n : Nat) :
229
+ goodFirstMass w accept good n =
230
+ eventMass w (fun s => accept s && good s) *
231
+ geometricMass (eventMass w (fun s => !(accept s))) n := by
232
+ unfold goodFirstMass eventMass
233
+ rw [Finset.sum_mul]
234
+ apply Finset.sum_congr rfl
235
+ intro s _
236
+ rw [firstHitWeight_some]
237
+ cases ha : accept s <;> cases hg : good s <;> simp [ha, hg, eventMass]
238
+
239
+ theorem goodFirstMass_exact (w : σ → ℝ) (accept good : σ → Bool)
240
+ (hw : ∑ s, w s = 1) (ha : eventMass w accept ≠ 0) (n : Nat) :
241
+ goodFirstMass w accept good n =
242
+ eventMass w (fun s => accept s && good s) / eventMass w accept *
243
+ (1 - eventMass w (fun s => !(accept s)) ^ n) := by
244
+ rw [goodFirstMass_eq]
245
+ have hc := eventMass_complement w accept hw
246
+ have hg := geometricMass_identity (eventMass w (fun s => !(accept s))) n
247
+ have hgeom : eventMass w accept *
248
+ geometricMass (eventMass w (fun s => !(accept s))) n =
249
+ 1 - eventMass w (fun s => !(accept s)) ^ n := by
250
+ have heq : eventMass w accept = 1 - eventMass w (fun s => !(accept s)) := by linarith
251
+ rw [heq, hg]
252
+ rw [← hgeom]
253
+ field_simp
254
+
255
+ theorem commonMass_le_acceptMass (w : σ → ℝ) (accept good : σ → Bool)
256
+ (hw : ∀ s, 0 ≤ w s) :
257
+ eventMass w (fun s => accept s && good s) ≤ eventMass w accept := by
258
+ apply Finset.sum_le_sum
259
+ intro s _
260
+ cases ha : accept s <;> cases hg : good s <;> simp [ha, hg, hw s]
261
+
262
+ theorem goodFirstMass_lower_bound (w : σ → ℝ) (accept good : σ → Bool)
263
+ (hw : ∀ s, 0 ≤ w s) (hw_sum : ∑ s, w s = 1)
264
+ (ha : 0 < eventMass w accept) (n : Nat) :
265
+ eventMass w (fun s => accept s && good s) / eventMass w accept -
266
+ eventMass w (fun s => !(accept s)) ^ n ≤ goodFirstMass w accept good n := by
267
+ rw [goodFirstMass_exact w accept good hw_sum (ne_of_gt ha) n]
268
+ have hratio : eventMass w (fun s => accept s && good s) / eventMass w accept ≤ 1 := by
269
+ apply (div_le_one ha).2
270
+ exact commonMass_le_acceptMass w accept good hw
271
+ have htail : 0 ≤ eventMass w (fun s => !(accept s)) ^ n :=
272
+ pow_nonneg (eventMass_nonneg w (fun s => !(accept s)) hw) n
273
+ nlinarith
274
+
275
+ def traceAverage (w : σ → ℝ) : Nat → (List σ → ℝ) → ℝ
276
+ | 0, observable => observable []
277
+ | n + 1, observable => ∑ s, w s * traceAverage w n (fun tail => observable (s :: tail))
278
+
279
+ theorem traceAverage_const (w : σ → ℝ) (hw : ∑ s, w s = 1) (n : Nat) (c : ℝ) :
280
+ traceAverage w n (fun _ => c) = c := by
281
+ induction n with
282
+ | zero => rfl
283
+ | succ n ih => simp [traceAverage, ih, ← Finset.sum_mul, hw]
284
+
285
+ theorem traceAverage_mono (w : σ → ℝ) (hw : ∀ s, 0 ≤ w s) (n : Nat)
286
+ (f g : List σ → ℝ) (hfg : ∀ xs, f xs ≤ g xs) :
287
+ traceAverage w n f ≤ traceAverage w n g := by
288
+ induction n generalizing f g with
289
+ | zero => exact hfg []
290
+ | succ n ih =>
291
+ apply Finset.sum_le_sum
292
+ intro s _
293
+ exact mul_le_mul_of_nonneg_left
294
+ (ih (fun tail => f (s :: tail)) (fun tail => g (s :: tail))
295
+ (fun tail => hfg (s :: tail))) (hw s)
296
+
297
+ theorem traceAverage_sum {ι : Type*} [Fintype ι] (w : σ → ℝ) (n : Nat)
298
+ (f : ι → List σ → ℝ) :
299
+ traceAverage w n (fun xs => ∑ i, f i xs) = ∑ i, traceAverage w n (f i) := by
300
+ induction n generalizing f with
301
+ | zero => rfl
302
+ | succ n ih =>
303
+ simp only [traceAverage]
304
+ simp_rw [ih, Finset.mul_sum]
305
+ exact Finset.sum_comm
306
+
307
+ variable [DecidableEq σ]
308
+
309
+ theorem firstAccepted_law (w : σ → ℝ) (accept : σ → Bool)
310
+ (hw : ∑ s, w s = 1) (n : Nat) (output : Option σ) :
311
+ traceAverage w n (fun proposals =>
312
+ if firstAccepted accept proposals = output then 1 else 0) =
313
+ firstHitWeight w accept n output := by
314
+ classical
315
+ induction n generalizing output with
316
+ | zero => cases output <;> simp [traceAverage, firstAccepted, firstHitWeight]
317
+ | succ n ih =>
318
+ have hstep : traceAverage w (n + 1) (fun proposals =>
319
+ if firstAccepted accept proposals = output then 1 else 0) =
320
+ ∑ s, w s * (if accept s then (if some s = output then 1 else 0)
321
+ else firstHitWeight w accept n output) := by
322
+ unfold traceAverage
323
+ apply Finset.sum_congr rfl
324
+ intro s _
325
+ congr 1
326
+ by_cases hs : accept s = true
327
+ · simp [firstAccepted, hs, traceAverage_const w hw]
328
+ · simpa [firstAccepted, hs] using ih output
329
+ rw [hstep]
330
+ cases output with
331
+ | none =>
332
+ simp only [Option.some_ne_none, ite_false, firstHitWeight]
333
+ rw [eventMass, Finset.sum_mul]
334
+ apply Finset.sum_congr rfl
335
+ intro s _
336
+ cases accept s <;> simp
337
+ | some t =>
338
+ simp only [Option.some.injEq, firstHitWeight]
339
+ calc
340
+ ∑ s, w s * (if accept s then (if s = t then 1 else 0)
341
+ else firstHitWeight w accept n (some t)) =
342
+ ∑ s, ((if s = t then (if accept s then w s else 0) else 0) +
343
+ (if !(accept s) then w s else 0) * firstHitWeight w accept n (some t)) := by
344
+ apply Finset.sum_congr rfl
345
+ intro s _
346
+ by_cases he : s = t
347
+ · subst s
348
+ by_cases hs : accept t = true <;> simp [hs]
349
+ · by_cases hs : accept s = true <;> simp [hs, he]
350
+ _ = (if accept t then w t else 0) +
351
+ eventMass w (fun s => !(accept s)) * firstHitWeight w accept n (some t) := by
352
+ rw [Finset.sum_add_distrib, ← Finset.sum_mul]
353
+ simp [eventMass]
354
+
355
+ def goodFirstIndicator (accept good : σ → Bool) (proposals : List σ) : ℝ :=
356
+ match firstAccepted accept proposals with
357
+ | none => 0
358
+ | some s => if good s then 1 else 0
359
+
360
+ theorem goodFirstIndicator_expansion (accept good : σ → Bool) (proposals : List σ) :
361
+ goodFirstIndicator accept good proposals =
362
+ ∑ s, if good s then (if firstAccepted accept proposals = some s then 1 else 0) else 0 := by
363
+ classical
364
+ cases h : firstAccepted accept proposals with
365
+ | none => simp [goodFirstIndicator, h]
366
+ | some t =>
367
+ simp only [goodFirstIndicator, h, Option.some.injEq]
368
+ calc
369
+ (if good t then (1 : ℝ) else 0) =
370
+ ∑ s, if t = s then (if good s then (1 : ℝ) else 0) else 0 := by simp
371
+ _ = ∑ s, if good s then (if t = s then (1 : ℝ) else 0) else 0 := by
372
+ apply Finset.sum_congr rfl
373
+ intro s _
374
+ by_cases hg : good s = true <;> by_cases ht : t = s <;> simp [hg, ht]
375
+
376
+ theorem goodFirstIndicator_law (w : σ → ℝ) (accept good : σ → Bool)
377
+ (hw : ∑ s, w s = 1) (n : Nat) :
378
+ traceAverage w n (goodFirstIndicator accept good) = goodFirstMass w accept good n := by
379
+ classical
380
+ change traceAverage w n (fun xs => goodFirstIndicator accept good xs) = _
381
+ simp_rw [goodFirstIndicator_expansion]
382
+ rw [traceAverage_sum]
383
+ unfold goodFirstMass
384
+ apply Finset.sum_congr rfl
385
+ intro s _
386
+ by_cases hg : good s = true
387
+ · simpa [hg] using firstAccepted_law w accept hw n (some s)
388
+ · simp [hg, traceAverage_const w hw]
389
+
390
+ structure ThresholdInterval where
391
+ lo : ℝ
392
+ hi : ℝ
393
+ valid : lo ≤ hi
394
+
395
+ def splitPoint (I : ThresholdInterval) (t : ℝ) : ℝ := max I.lo (min t I.hi)
396
+
397
+ def splitLeft (I : ThresholdInterval) (t : ℝ) : ThresholdInterval :=
398
+ ⟨I.lo, splitPoint I t, le_max_left _ _⟩
399
+
400
+ def splitRight (I : ThresholdInterval) (t : ℝ) : ThresholdInterval :=
401
+ ⟨splitPoint I t, I.hi, max_le I.valid (min_le_right _ _)⟩
402
+
403
+ def cutAt (r : ℝ) (I : ThresholdInterval) : Prop := I.hi ≤ r ∨ r ≤ I.lo
404
+
405
+ def intervalCDF (r : ℝ) (I : ThresholdInterval) : ℝ := min r I.hi - min r I.lo
406
+
407
+ theorem split_cdf (I : ThresholdInterval) (t r : ℝ) :
408
+ intervalCDF r (splitLeft I t) + intervalCDF r (splitRight I t) = intervalCDF r I := by
409
+ unfold intervalCDF splitLeft splitRight
410
+ ring
411
+
412
+ theorem accepted_interval_mass (I : ThresholdInterval) (r : ℝ) (hc : cutAt r I) :
413
+ (if I.lo < r then I.hi - I.lo else 0) = intervalCDF r I := by
414
+ by_cases hl : I.lo < r
415
+ · have hu : I.hi ≤ r := hc.resolve_right (not_le_of_gt hl)
416
+ simp [hl, intervalCDF, min_eq_right hu, min_eq_right (le_of_lt hl)]
417
+ · have hr : r ≤ I.lo := le_of_not_gt hl
418
+ simp [hl, intervalCDF, min_eq_left hr, min_eq_left (hr.trans I.valid)]
419
+
420
+ theorem splitLeft_cut (I : ThresholdInterval) (t : ℝ) : cutAt t (splitLeft I t) := by
421
+ by_cases h : I.lo ≤ t
422
+ · exact Or.inl (max_le h (min_le_left _ _))
423
+ · exact Or.inr (le_of_lt (lt_of_not_ge h))
424
+
425
+ theorem splitRight_cut (I : ThresholdInterval) (t : ℝ) : cutAt t (splitRight I t) := by
426
+ by_cases h : t ≤ I.hi
427
+ · right
428
+ change t ≤ max I.lo (min t I.hi)
429
+ rw [min_eq_left h]
430
+ exact le_max_right _ _
431
+ · exact Or.inl (le_of_lt (lt_of_not_ge h))
432
+
433
+ theorem splitLeft_preserves_cut (I : ThresholdInterval) (t r : ℝ) (h : cutAt r I) :
434
+ cutAt r (splitLeft I t) := by
435
+ rcases h with h | h
436
+ · exact Or.inl ((max_le I.valid (min_le_right _ _)).trans h)
437
+ · exact Or.inr h
438
+
439
+ theorem splitRight_preserves_cut (I : ThresholdInterval) (t r : ℝ) (h : cutAt r I) :
440
+ cutAt r (splitRight I t) := by
441
+ rcases h with h | h
442
+ · exact Or.inl h
443
+ · exact Or.inr (h.trans (le_max_left _ _))
444
+
445
+ def splitAll (t : ℝ) : List ThresholdInterval → List ThresholdInterval
446
+ | [] => []
447
+ | I :: rest => splitLeft I t :: splitRight I t :: splitAll t rest
448
+
449
+ def unitThresholdInterval : ThresholdInterval := ⟨0, 1, by norm_num⟩
450
+
451
+ def thresholdPartition : List ℝ → List ThresholdInterval
452
+ | [] => [unitThresholdInterval]
453
+ | t :: rest => splitAll t (thresholdPartition rest)
454
+
455
+ def sumOnIntervals (f : ThresholdInterval → ℝ) : List ThresholdInterval → ℝ
456
+ | [] => 0
457
+ | I :: rest => f I + sumOnIntervals f rest
458
+
459
+ theorem sumOn_splitAll (f : ThresholdInterval → ℝ) (t : ℝ)
460
+ (hf : ∀ I, f (splitLeft I t) + f (splitRight I t) = f I)
461
+ (intervals : List ThresholdInterval) :
462
+ sumOnIntervals f (splitAll t intervals) = sumOnIntervals f intervals := by
463
+ induction intervals with
464
+ | nil => rfl
465
+ | cons I rest ih =>
466
+ simp only [splitAll, sumOnIntervals, ih]
467
+ rw [← add_assoc, hf]
468
+
469
+ theorem partition_sum (f : ThresholdInterval → ℝ)
470
+ (hf : ∀ t I, f (splitLeft I t) + f (splitRight I t) = f I)
471
+ (thresholds : List ℝ) :
472
+ sumOnIntervals f (thresholdPartition thresholds) = f unitThresholdInterval := by
473
+ induction thresholds with
474
+ | nil => simp [thresholdPartition, sumOnIntervals]
475
+ | cons t rest ih =>
476
+ rw [thresholdPartition, sumOn_splitAll f t (hf t), ih]
477
+
478
+ theorem partition_total_mass (thresholds : List ℝ) :
479
+ sumOnIntervals (fun I => I.hi - I.lo) (thresholdPartition thresholds) = 1 := by
480
+ have h := partition_sum (fun I => I.hi - I.lo)
481
+ (fun t I => by simp only [splitLeft, splitRight]; ring) thresholds
482
+ simpa [unitThresholdInterval] using h
483
+
484
+ theorem partition_cdf (thresholds : List ℝ) (r : ℝ) (h0 : 0 ≤ r) (h1 : r ≤ 1) :
485
+ sumOnIntervals (intervalCDF r) (thresholdPartition thresholds) = r := by
486
+ have h := partition_sum (intervalCDF r) (fun t I => split_cdf I t r) thresholds
487
+ simpa [intervalCDF, unitThresholdInterval, min_eq_left h1, min_eq_right h0] using h
488
+
489
+ theorem splitAll_new_cuts (intervals : List ThresholdInterval) (t : ℝ) :
490
+ ∀ I ∈ splitAll t intervals, cutAt t I := by
491
+ induction intervals with
492
+ | nil => intro I h; simp [splitAll] at h
493
+ | cons J rest ih =>
494
+ intro I h
495
+ rcases List.mem_cons.mp h with h | h
496
+ · subst I; exact splitLeft_cut J t
497
+ · rcases List.mem_cons.mp h with h | h
498
+ · subst I; exact splitRight_cut J t
499
+ · exact ih I h
500
+
501
+ theorem splitAll_preserves_cuts (intervals : List ThresholdInterval) (t r : ℝ) :
502
+ (∀ I ∈ intervals, cutAt r I) → ∀ I ∈ splitAll t intervals, cutAt r I := by
503
+ induction intervals with
504
+ | nil => intro _ I h; simp [splitAll] at h
505
+ | cons J rest ih =>
506
+ intro hc I h
507
+ have hJ : cutAt r J := hc J (by simp)
508
+ have hrest : ∀ K ∈ rest, cutAt r K := fun K hK => hc K (by simp [hK])
509
+ rcases List.mem_cons.mp h with h | h
510
+ · subst I; exact splitLeft_preserves_cut J t r hJ
511
+ · rcases List.mem_cons.mp h with h | h
512
+ · subst I; exact splitRight_preserves_cut J t r hJ
513
+ · exact ih hrest I h
514
+
515
+ theorem partition_cuts (thresholds : List ℝ) (r : ℝ) :
516
+ r ∈ thresholds → ∀ I ∈ thresholdPartition thresholds, cutAt r I := by
517
+ induction thresholds with
518
+ | nil => intro hr; simp at hr
519
+ | cons t rest ih =>
520
+ intro hr
521
+ rcases List.mem_cons.mp hr with h | h
522
+ · subst r; exact splitAll_new_cuts (thresholdPartition rest) t
523
+ · exact splitAll_preserves_cuts (thresholdPartition rest) t r (ih h)
524
+
525
+ theorem sumOnIntervals_congr (f g : ThresholdInterval → ℝ) (intervals : List ThresholdInterval) :
526
+ (∀ I ∈ intervals, f I = g I) → sumOnIntervals f intervals = sumOnIntervals g intervals := by
527
+ induction intervals with
528
+ | nil => intro _; rfl
529
+ | cons J rest ih =>
530
+ intro h
531
+ have hJ := h J (by simp)
532
+ have hr : ∀ I ∈ rest, f I = g I := fun I hI => h I (by simp [hI])
533
+ simp only [sumOnIntervals, hJ, ih hr]
534
+
535
+ theorem partition_acceptance_mass (thresholds : List ℝ) (r : ℝ)
536
+ (hr : r ∈ thresholds) (h0 : 0 ≤ r) (h1 : r ≤ 1) :
537
+ sumOnIntervals (fun I => if I.lo < r then I.hi - I.lo else 0)
538
+ (thresholdPartition thresholds) = r := by
539
+ calc
540
+ _ = sumOnIntervals (intervalCDF r) (thresholdPartition thresholds) :=
541
+ sumOnIntervals_congr _ _ _ (fun I hI =>
542
+ accepted_interval_mass I r (partition_cuts thresholds r hr I hI))
543
+ _ = r := partition_cdf thresholds r h0 h1
544
+
545
+ theorem sum_interval_get (f : ThresholdInterval → ℝ) (intervals : List ThresholdInterval) :
546
+ (∑ i : Fin intervals.length, f intervals[i]) = sumOnIntervals f intervals := by
547
+ induction intervals with
548
+ | nil => simp [sumOnIntervals]
549
+ | cons I rest ih =>
550
+ simpa [Fin.sum_univ_succ, sumOnIntervals] using congrArg (fun x : ℝ => f I + x) ih
551
+
552
+ variable {α : Type*} [Fintype α]
553
+
554
+ private theorem sum_div_const {ι : Type*} [Fintype ι] (f : ι → ℝ) (c : ℝ) :
555
+ (∑ i, f i) / c = ∑ i, f i / c := by
556
+ simp only [div_eq_mul_inv, Finset.sum_mul]
557
+
558
+ abbrev RectangleSeed (thresholds : List ℝ) (α : Type*) :=
559
+ α × Fin (thresholdPartition thresholds).length
560
+
561
+ def rectangleWeight (thresholds : List ℝ) (seed : RectangleSeed thresholds α) : ℝ :=
562
+ ((thresholdPartition thresholds)[seed.2].hi - (thresholdPartition thresholds)[seed.2].lo) /
563
+ (Fintype.card α : ℝ)
564
+
565
+ def rectangleAccept (thresholds : List ℝ) (density : α → ℝ)
566
+ (seed : RectangleSeed thresholds α) : Bool :=
567
+ decide ((thresholdPartition thresholds)[seed.2].lo < density seed.1)
568
+
569
+ theorem rectangleWeight_nonnegative (thresholds : List ℝ) (seed : RectangleSeed thresholds α) :
570
+ 0 ≤ rectangleWeight thresholds seed :=
571
+ div_nonneg (sub_nonneg.mpr ((thresholdPartition thresholds)[seed.2].valid)) (by positivity)
572
+
573
+ theorem rectangleWeight_normalized [Nonempty α] (thresholds : List ℝ) :
574
+ ∑ seed : RectangleSeed thresholds α, rectangleWeight thresholds seed = 1 := by
575
+ rw [Fintype.sum_prod_type]
576
+ have hrow (a : α) : (∑ i, rectangleWeight thresholds (a, i)) =
577
+ 1 / (Fintype.card α : ℝ) := by
578
+ unfold rectangleWeight
579
+ rw [← sum_div_const, sum_interval_get (fun I => I.hi - I.lo), partition_total_mass]
580
+ simp_rw [hrow]
581
+ have hc : (Fintype.card α : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero
582
+ simp [hc]
583
+
584
+ def rectangleDistribution [Nonempty α] (thresholds : List ℝ) :
585
+ Games.FiniteDistribution (RectangleSeed thresholds α) where
586
+ weight := rectangleWeight thresholds
587
+ nonnegative := rectangleWeight_nonnegative thresholds
588
+ normalized := rectangleWeight_normalized thresholds
589
+
590
+ theorem rectangle_row_mass (thresholds : List ℝ) (density : α → ℝ) (a : α)
591
+ (hm : density a ∈ thresholds) (h0 : 0 ≤ density a) (h1 : density a ≤ 1) :
592
+ (∑ i, if rectangleAccept thresholds density (a, i) then
593
+ rectangleWeight thresholds (a, i) else 0) = density a / (Fintype.card α : ℝ) := by
594
+ calc
595
+ _ = (∑ i : Fin (thresholdPartition thresholds).length,
596
+ if (thresholdPartition thresholds)[i].lo < density a then
597
+ (thresholdPartition thresholds)[i].hi - (thresholdPartition thresholds)[i].lo else 0) /
598
+ (Fintype.card α : ℝ) := by
599
+ rw [sum_div_const]
600
+ apply Finset.sum_congr rfl
601
+ intro i _
602
+ simp [rectangleAccept, rectangleWeight, ite_div]
603
+ _ = density a / (Fintype.card α : ℝ) := by
604
+ rw [sum_interval_get (fun I => if I.lo < density a then I.hi - I.lo else 0),
605
+ partition_acceptance_mass thresholds (density a) hm h0 h1]
606
+
607
+ theorem rectangle_acceptance_mass (thresholds : List ℝ) (density : α → ℝ)
608
+ (hm : ∀ a, density a ∈ thresholds) (h0 : ∀ a, 0 ≤ density a)
609
+ (h1 : ∀ a, density a ≤ 1) :
610
+ eventMass (rectangleWeight thresholds) (rectangleAccept thresholds density) =
611
+ (∑ a, density a) / (Fintype.card α : ℝ) := by
612
+ unfold eventMass
613
+ rw [Fintype.sum_prod_type]
614
+ simp_rw [rectangle_row_mass thresholds density _ (hm _) (h0 _) (h1 _)]
615
+ rw [sum_div_const]
616
+
617
+ theorem rectangle_label_mass [DecidableEq α] (thresholds : List ℝ) (density : α → ℝ) (a : α)
618
+ (hm : ∀ x, density x ∈ thresholds) (h0 : ∀ x, 0 ≤ density x)
619
+ (h1 : ∀ x, density x ≤ 1) :
620
+ eventMass (rectangleWeight thresholds)
621
+ (fun seed => rectangleAccept thresholds density seed && decide (seed.1 = a)) =
622
+ density a / (Fintype.card α : ℝ) := by
623
+ unfold eventMass
624
+ rw [Fintype.sum_prod_type]
625
+ calc
626
+ _ = ∑ x : α, if x = a then density x / (Fintype.card α : ℝ) else 0 := by
627
+ apply Finset.sum_congr rfl
628
+ intro x _
629
+ by_cases hx : x = a
630
+ · simpa [hx] using rectangle_row_mass thresholds density x (hm x) (h0 x) (h1 x)
631
+ · simp [hx]
632
+ _ = density a / (Fintype.card α : ℝ) := by simp
633
+
634
+ omit [Fintype α] in theorem rectangle_and (thresholds : List ℝ) (p q : α → ℝ) :
635
+ (fun seed => rectangleAccept thresholds p seed && rectangleAccept thresholds q seed) =
636
+ rectangleAccept thresholds (fun a => min (p a) (q a)) := by
637
+ funext seed
638
+ simp [rectangleAccept]
639
+
640
+ omit [Fintype α] in theorem rectangle_or (thresholds : List ℝ) (p q : α → ℝ) :
641
+ (fun seed => rectangleAccept thresholds p seed || rectangleAccept thresholds q seed) =
642
+ rectangleAccept thresholds (fun a => max (p a) (q a)) := by
643
+ funext seed
644
+ simp [rectangleAccept]
645
+
646
+ theorem min_mem_thresholds (thresholds : List ℝ) {x y : ℝ} (hx : x ∈ thresholds)
647
+ (hy : y ∈ thresholds) : min x y ∈ thresholds := by
648
+ by_cases h : x ≤ y <;> simp [min_def, h, hx, hy]
649
+
650
+ theorem max_mem_thresholds (thresholds : List ℝ) {x y : ℝ} (hx : x ∈ thresholds)
651
+ (hy : y ∈ thresholds) : max x y ∈ thresholds := by
652
+ by_cases h : x ≤ y <;> simp [max_def, h, hx, hy]
653
+
654
+ theorem rectangle_union_mass (thresholds : List ℝ) (p q : α → ℝ)
655
+ (hpm : ∀ a, p a ∈ thresholds) (hqm : ∀ a, q a ∈ thresholds)
656
+ (hp0 : ∀ a, 0 ≤ p a) (_hq0 : ∀ a, 0 ≤ q a)
657
+ (hp1 : ∀ a, p a ≤ 1) (hq1 : ∀ a, q a ≤ 1) :
658
+ eventMass (rectangleWeight thresholds)
659
+ (fun seed => rectangleAccept thresholds p seed || rectangleAccept thresholds q seed) =
660
+ unionMass p q / (Fintype.card α : ℝ) := by
661
+ rw [rectangle_or]
662
+ exact rectangle_acceptance_mass thresholds _
663
+ (fun a => max_mem_thresholds thresholds (hpm a) (hqm a))
664
+ (fun a => (hp0 a).trans (le_max_left _ _)) (fun a => max_le (hp1 a) (hq1 a))
665
+
666
+ theorem rectangle_common_label_mass [DecidableEq α] (thresholds : List ℝ)
667
+ (p q : α → ℝ) (a : α)
668
+ (hpm : ∀ x, p x ∈ thresholds) (hqm : ∀ x, q x ∈ thresholds)
669
+ (hp0 : ∀ x, 0 ≤ p x) (hq0 : ∀ x, 0 ≤ q x)
670
+ (hp1 : ∀ x, p x ≤ 1) (_hq1 : ∀ x, q x ≤ 1) :
671
+ eventMass (rectangleWeight thresholds)
672
+ (fun seed => (rectangleAccept thresholds p seed && rectangleAccept thresholds q seed) &&
673
+ decide (seed.1 = a)) = min (p a) (q a) / (Fintype.card α : ℝ) := by
674
+ have hand := congrFun (rectangle_and thresholds p q)
675
+ simp_rw [hand]
676
+ exact rectangle_label_mass thresholds _ a
677
+ (fun x => min_mem_thresholds thresholds (hpm x) (hqm x))
678
+ (fun x => le_min (hp0 x) (hq0 x)) (fun x => (min_le_left _ _).trans (hp1 x))
679
+
680
+ end
681
+
682
+ end MinUncutGames.Foundations.CorrelatedSampling
683
+
684
+ end OAI
lean/OAI/Computability/MinUncut/Games/FinalCNFHeader.lean ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.FinalCNFPattern
3
+ import OAI.Computability.MinUncut.Machines.RawInitialMachineFinish
4
+
5
+ namespace OAI
6
+
7
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
8
+
9
+ open Turing
10
+ open PCP.AlphabetTable
11
+
12
+ def headerFrame (input archive vertices darts rowIndex tail head accumulator : List Bool) :
13
+ Tape → List Bool
14
+ | .input => input
15
+ | .archive => archive
16
+ | .vertices => vertices
17
+ | .darts => darts
18
+ | .rowIndex => rowIndex
19
+ | .tail => tail
20
+ | .head => head
21
+ | .accumulator => accumulator
22
+ | _ => []
23
+
24
+ def headerInputTapes (input : List Bool) : Tape → List Bool :=
25
+ headerFrame input [] [] [] [] [] [] []
26
+
27
+ def headerResultTapes (n m : Nat) (rowsBits : List Bool) : Tape → List Bool :=
28
+ headerFrame rowsBits (encodeWords [n, m] ++ rowsBits)
29
+ (encodeWord n) (encodeWord m) (encodeWord 0) [] []
30
+ (encodeWords [6 * n + 36864 * m, 40960 * m]).reverse
31
+
32
+ @[simp] theorem headerResultTapes_input (n m : Nat) (rowsBits : List Bool) :
33
+ headerResultTapes n m rowsBits .input = rowsBits := rfl
34
+
35
+ @[simp] theorem headerResultTapes_archive (n m : Nat) (rowsBits : List Bool) :
36
+ headerResultTapes n m rowsBits .archive = encodeWords [n, m] ++ rowsBits := rfl
37
+
38
+ @[simp] theorem headerResultTapes_accumulator (n m : Nat) (rowsBits : List Bool) :
39
+ headerResultTapes n m rowsBits .accumulator =
40
+ (encodeWords [6 * n + 36864 * m, 40960 * m]).reverse := rfl
41
+
42
+ @[simp] theorem headerResultTapes_rowIndex (n m : Nat) (rowsBits : List Bool) :
43
+ headerResultTapes n m rowsBits .rowIndex = encodeWord 0 := rfl
44
+
45
+ noncomputable def headerTimePolynomial : Polynomial Nat :=
46
+ Polynomial.C 25 * Polynomial.X + Polynomial.C 52
47
+
48
+ @[simp] theorem headerTimePolynomial_eval (length : Nat) :
49
+ headerTimePolynomial.eval length = 25 * length + 52 := by
50
+ simp [headerTimePolynomial]
51
+
52
+ def headerInTime (rowPlan : Plan) (n m : Nat) (rowsBits : List Bool) (ambient : Ambient) :
53
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
54
+ ⟨some .copyFirst, ((ambient, ()), none),
55
+ headerInputTapes (encodeWords [n, m] ++ rowsBits)⟩
56
+ (some ⟨some .guard, ((ambient, ()), none), headerResultTapes n m rowsBits⟩)
57
+ (headerTimePolynomial.eval (encodeWords [n, m] ++ rowsBits).length) := by
58
+ let word := encodeWords [n, m] ++ rowsBits
59
+ let bits := encodeWords [6 * n + 36864 * m, 40960 * m]
60
+ let b₀ := headerInputTapes word
61
+ let b₁ := headerFrame word word [] [] [] [] [] []
62
+ let b₂ := headerFrame (encodeWord m ++ rowsBits) word (encodeWord n) [] [] [] [] []
63
+ let b₃ := headerFrame rowsBits word (encodeWord n) (encodeWord m) [] [] [] []
64
+ let b₄ := headerFrame rowsBits word (encodeWord n) (encodeWord m)
65
+ (encodeWord 0) (encodeWord 0) (encodeWord 0) []
66
+ let b₅ := headerFrame rowsBits word (encodeWord n) (encodeWord m)
67
+ (encodeWord 0) (encodeWord 0) (encodeWord 0) bits.reverse
68
+ let b₆ := headerFrame rowsBits word (encodeWord n) (encodeWord m)
69
+ (encodeWord 0) [] (encodeWord 0) bits.reverse
70
+ let b₇ := headerResultTapes n m rowsBits
71
+ have h₀ : Function.update b₀ Tape.archive (b₀ .input ++ b₀ .archive) = b₁ := by
72
+ funext tape; cases tape <;> simp [b₀, b₁, headerInputTapes, headerFrame]
73
+ have h₁ : Hastad.SourceMachine.fieldTapes Tape.input Tape.vertices b₁
74
+ (encodeWord m ++ rowsBits) (encodeWord n ++ b₁ .vertices) = b₂ := by
75
+ funext tape; cases tape <;> simp [Hastad.SourceMachine.fieldTapes, b₁, b₂, headerFrame]
76
+ have h₂ : Hastad.SourceMachine.fieldTapes Tape.input Tape.darts b₂
77
+ rowsBits (encodeWord m ++ b₂ .darts) = b₃ := by
78
+ funext tape; cases tape <;> simp [Hastad.SourceMachine.fieldTapes, b₂, b₃, headerFrame]
79
+ have h₄ : Emitter.resultTapes Tape.accumulator b₄
80
+ (Emitter.prefixBits (Emitter.listCommands headerPlan) (values n m 0 0 0)
81
+ ambient headerPlan.length) = b₅ := by
82
+ rw [Emitter.bits_listCommands, headerPlan_bits]
83
+ funext tape; cases tape <;> simp [Emitter.resultTapes, b₄, b₅, bits, headerFrame]
84
+ have h₅ : Function.update b₅ Tape.tail [] = b₆ := by
85
+ funext tape; cases tape <;> simp [b₅, b₆, headerFrame]
86
+ have h₆ : Function.update b₆ Tape.head [] = b₇ := by
87
+ funext tape; cases tape <;> simp [b₆, b₇, headerResultTapes, bits, word, headerFrame]
88
+ have hn : n ≤ word.length := by
89
+ simp only [word, List.length_append, encodeWords_length, List.sum_cons,
90
+ List.sum_nil, List.length_cons, List.length_nil] ; omega
91
+ have hm : m ≤ word.length := by
92
+ simp only [word, List.length_append, encodeWords_length, List.sum_cons,
93
+ List.sum_nil, List.length_cons, List.length_nil] ; omega
94
+ let p₀ := MachineCopy.copyInTime Tape.input Tape.archive Tape.scratch
95
+ (by decide) (by decide) (by decide) false .copyFirst .copySecond (some .startVertices)
96
+ (program headerPlan rowPlan) rfl rfl b₀ (by rfl) (ambient, ()) none
97
+ have p₀' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
98
+ ⟨some .copyFirst, ((ambient, ()), none), b₀⟩
99
+ (some ⟨some .startVertices, ((ambient, ()), none), b₁⟩) (2 * (word.length + 1)) := by
100
+ have h := p₀
101
+ rw [h₀] at h
102
+ simpa only [show b₀ .input = word from rfl] using h
103
+ let p₁ := Hastad.SourceMachine.fieldInTime Tape.input Tape.vertices (by decide)
104
+ .startVertices .readVertices (some .startDarts) (program headerPlan rowPlan)
105
+ rfl rfl b₁ n (encodeWord m ++ rowsBits)
106
+ (by simp [b₁, headerFrame, word, encodeWords, List.append_assoc]) (ambient, ()) none
107
+ have p₁' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
108
+ ⟨some .startVertices, ((ambient, ()), none), b₁⟩
109
+ (some ⟨some .startDarts, ((ambient, ()), none), b₂⟩) (n + 2) := by
110
+ simpa only [h₁] using p₁
111
+ let p₂ := Hastad.SourceMachine.fieldInTime Tape.input Tape.darts (by decide)
112
+ .startDarts .readDarts (some .seedIndex) (program headerPlan rowPlan)
113
+ rfl rfl b₂ m rowsBits rfl (ambient, ()) none
114
+ have p₂' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
115
+ ⟨some .startDarts, ((ambient, ()), none), b₂⟩
116
+ (some ⟨some .seedIndex, ((ambient, ()), none), b₃⟩) (m + 2) := by
117
+ simpa only [h₂] using p₂
118
+ let p₃ : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
119
+ ⟨some .seedIndex, ((ambient, ()), none), b₃⟩
120
+ (some ⟨some (.header (Emitter.labelAt headerPlan.length 36864 0 .entry)),
121
+ ((ambient, ()), none), b₄⟩) 1 := {
122
+ steps := 1
123
+ evals_in_steps := by
124
+ simp only [Function.iterate_one]
125
+ change TM2.step (program headerPlan rowPlan)
126
+ ⟨some .seedIndex, ((ambient, ()), none), b₃⟩ = _
127
+ have ht : Function.update (Function.update (Function.update b₃ Tape.rowIndex [false])
128
+ Tape.tail [false]) Tape.head [false] = b₄ := by
129
+ funext tape; cases tape <;> simp [b₃, b₄, headerFrame, encodeWord]
130
+ simp only [TM2.step, program, TM2.stepAux]
131
+ apply congrArg some
132
+ exact congrArg (TM2.Cfg.mk _ _) ht
133
+ steps_le_m := Nat.le_refl _ }
134
+ let p₄ := Emitter.planInTime (Emitter.listCommands headerPlan) source Tape.scratch
135
+ Tape.accumulator source_ne_scratch source_ne_accumulator (by decide)
136
+ Label.header (some .headerClearTail) (program headerPlan rowPlan) (fun _ => rfl)
137
+ (values n m 0 0 0) b₄
138
+ (by intro i; fin_cases i <;> rfl) rfl ambient word.length
139
+ (by
140
+ intro i
141
+ fin_cases i
142
+ · exact hn
143
+ · exact hm
144
+ · exact Nat.zero_le _
145
+ · exact Nat.zero_le _
146
+ · exact Nat.zero_le _)
147
+ have p₄' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
148
+ ⟨some (.header (Emitter.labelAt headerPlan.length 36864 0 .entry)),
149
+ ((ambient, ()), none), b₄⟩
150
+ (some ⟨some .headerClearTail, ((ambient, ()), none), b₅⟩)
151
+ (7 * (3 * (word.length + 1) + 3) + 1) := by
152
+ have h := p₄
153
+ rw [h₄] at h
154
+ simpa only [headerPlan_length] using h
155
+ let p₅ := MachineLookup.discardInTime Tape.tail .headerClearTail .headerClearHead
156
+ (program headerPlan rowPlan) rfl b₅ 0 [] (by simp [b₅, headerFrame]) (ambient, ()) none
157
+ have p₅' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
158
+ ⟨some .headerClearTail, ((ambient, ()), none), b₅⟩
159
+ (some ⟨some .headerClearHead, ((ambient, ()), none), b₆⟩) 1 := by
160
+ simpa only [h₅] using p₅
161
+ let p₆ := MachineLookup.discardInTime Tape.head .headerClearHead .guard
162
+ (program headerPlan rowPlan) rfl b₆ 0 [] (by simp [b₆, headerFrame]) (ambient, ()) none
163
+ have p₆' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
164
+ ⟨some .headerClearHead, ((ambient, ()), none), b₆⟩
165
+ (some ⟨some .guard, ((ambient, ()), none), b₇⟩) 1 := by
166
+ simpa only [h₆] using p₆
167
+ let p₀₁ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀' p₁'
168
+ let p₀₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁ p₂'
169
+ let p₀₁₂₃ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁₂ p₃
170
+ let p₀₁₂₃₄ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁₂₃ p₄'
171
+ let p₀₁₂₃₄₅ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁₂₃₄ p₅'
172
+ let p := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁₂₃₄₅ p₆'
173
+ exact {
174
+ toEvalsTo := p.toEvalsTo
175
+ steps_le_m := by
176
+ have h := p.steps_le_m
177
+ change _ ≤ headerTimePolynomial.eval word.length
178
+ rw [headerTimePolynomial_eval]
179
+ omega }
180
+
181
+ def tableRowsBits (table : PCP.GenericGraphTables.Table 64) : List Bool :=
182
+ encodeWords ((PCP.GenericGraphTables.rowList table).flatMap PCP.GenericGraphTables.rowWords)
183
+
184
+ theorem tableBits_header_rows (table : PCP.GenericGraphTables.Table 64) :
185
+ PCP.GenericGraphTables.tableBits table =
186
+ encodeWords [table.vertices, table.darts] ++ tableRowsBits table := by
187
+ simp only [PCP.GenericGraphTables.tableBits, PCP.GenericGraphTables.tableWords,
188
+ encodeWords_append, tableRowsBits]
189
+
190
+ def tableHeaderInTime (rowPlan : Plan) (table : PCP.GenericGraphTables.Table 64)
191
+ (ambient : Ambient) :
192
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan))
193
+ ⟨some .copyFirst, ((ambient, ()), none),
194
+ headerInputTapes (PCP.GenericGraphTables.tableBits table)⟩
195
+ (some ⟨some .guard, ((ambient, ()), none),
196
+ headerResultTapes table.vertices table.darts (tableRowsBits table)⟩)
197
+ (headerTimePolynomial.eval (PCP.GenericGraphTables.tableBits table).length) := by
198
+ rw [tableBits_header_rows]
199
+ exact headerInTime rowPlan table.vertices table.darts (tableRowsBits table) ambient
200
+
201
+ theorem headerInput_configuration (rowPlan : Plan) (input : List Bool) :
202
+ initList (machine headerPlan rowPlan) input =
203
+ ⟨some .copyFirst, ((((), fun _ => false), ()), none), headerInputTapes input⟩ := by
204
+ have ht : (initList (machine headerPlan rowPlan) input).stk = headerInputTapes input := by
205
+ funext tape
206
+ cases tape <;> simp [initList, machine, headerInputTapes, headerFrame]
207
+ all_goals rfl
208
+ exact congrArg (TM2.Cfg.mk _ _) ht
209
+
210
+ def initializedTableHeaderInTime (rowPlan : Plan) (table : PCP.GenericGraphTables.Table 64) :
211
+ StateTransition.EvalsToInTime (machine headerPlan rowPlan).step
212
+ (initList (machine headerPlan rowPlan) (PCP.GenericGraphTables.tableBits table))
213
+ (some ⟨some .guard, ((((), fun _ => false), ()), none),
214
+ headerResultTapes table.vertices table.darts (tableRowsBits table)⟩)
215
+ (headerTimePolynomial.eval (PCP.GenericGraphTables.tableBits table).length) := by
216
+ rw [headerInput_configuration]
217
+ exact tableHeaderInTime rowPlan table ((), fun _ => false)
218
+
219
+ open Turing PCP PCP.AlphabetTable
220
+
221
+ def endpointTapes (base : Tape → List Bool) (tail reverse : Nat) (rest : List Bool) :=
222
+ Hastad.SourceMachine.fieldTapes Tape.input Tape.reverseIndex
223
+ (Hastad.SourceMachine.fieldTapes Tape.input Tape.tail base
224
+ (encodeWord reverse ++ rest) (encodeWord tail ++ base .tail))
225
+ rest (encodeWord reverse ++ base .reverseIndex)
226
+
227
+ def endpointsInTime (headerPlan plan : Plan) (base : Tape → List Bool)
228
+ (tail reverse : Nat) (rest : List Bool)
229
+ (hinput : base .input = encodeWord tail ++ encodeWord reverse ++ rest)
230
+ (ambient : Ambient) :
231
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
232
+ ⟨some .startTail, ((ambient, ()), none), base⟩
233
+ (some ⟨some .headTableFirst, ((ambient, ()), none),
234
+ endpointTapes base tail reverse rest⟩) (tail + reverse + 4) := by
235
+ let first := Hastad.SourceMachine.fieldTapes Tape.input Tape.tail base
236
+ (encodeWord reverse ++ rest) (encodeWord tail ++ base .tail)
237
+ let run₁ := Hastad.SourceMachine.fieldInTime Tape.input Tape.tail (by decide)
238
+ .startTail .readTail (some .startReverse) (program headerPlan plan) rfl rfl
239
+ base tail (encodeWord reverse ++ rest) (by simpa only [List.append_assoc] using hinput)
240
+ (ambient, ()) none
241
+ have input₁ : first .input = encodeWord reverse ++ rest := by
242
+ simp [first, Hastad.SourceMachine.fieldTapes]
243
+ have reverse₁ : first .reverseIndex = base .reverseIndex := by
244
+ simp [first, Hastad.SourceMachine.fieldTapes]
245
+ let run₂ := Hastad.SourceMachine.fieldInTime Tape.input Tape.reverseIndex (by decide)
246
+ .startReverse .readReverse (some .headTableFirst) (program headerPlan plan) rfl rfl
247
+ first reverse rest input₁ (ambient, ()) none
248
+ have joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ run₂
249
+ simpa only [first, reverse₁, endpointTapes, Nat.add_assoc,
250
+ Nat.add_left_comm, Nat.add_comm] using joined
251
+
252
+ def relationInTime (headerPlan plan : Plan) (base : Tape → List Bool)
253
+ (relation : GraphTables.RelationTable) (rest : List Bool)
254
+ (hinput : base .input = encodeWords (GraphTables.relationWords relation) ++ rest)
255
+ (ambient : Ambient) :
256
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
257
+ ⟨some .readRelation, ((ambient, ()), none), base⟩
258
+ (some ⟨some (.row (Emitter.labelAt plan.length 36864 0 .entry)),
259
+ ((((), fun i => relation[i]), ()), none), Function.update base .input rest⟩) 1 where
260
+ steps := 1
261
+ evals_in_steps := by
262
+ change some (TM2.stepAux (program headerPlan plan .readRelation) _ _) = _
263
+ rw [program, stepAux_readRelationAt _ _ _ _ _ _ _ _ _ hinput]
264
+ steps_le_m := Nat.le_refl _
265
+
266
+ def emitInTime (headerPlan plan : Plan) (base : Tape → List Bool)
267
+ (operands : Fin 5 → Nat) (hoperands : ∀ i, base (source i) = encodeWord (operands i))
268
+ (hscratch : base .scratch = []) (ambient : Ambient)
269
+ (N : Nat) (hbounded : ∀ i, operands i ≤ N) :
270
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
271
+ ⟨some (.row (Emitter.labelAt plan.length 36864 0 .entry)),
272
+ ((ambient, ()), none), base⟩
273
+ (some ⟨some .clearTail, ((ambient, ()), none),
274
+ Function.update base .accumulator
275
+ ((plan.flatMap (Emitter.commandBits operands ambient)).reverse ++ base .accumulator)⟩)
276
+ (plan.length * (3 * (N + 1) + 3) + 1) := by
277
+ have run := Emitter.planInTime (Emitter.listCommands plan)
278
+ source Tape.scratch Tape.accumulator source_ne_scratch source_ne_accumulator (by decide)
279
+ Label.row (some .clearTail) (program headerPlan plan) (fun _ => rfl)
280
+ operands base hoperands hscratch ambient N hbounded
281
+ simpa only [Emitter.bits_listCommands, Emitter.resultTapes] using run
282
+
283
+ def finishTapes (base : Tape → List Bool) (row : Nat) : Tape → List Bool :=
284
+ Function.update
285
+ (Function.update (Function.update (Function.update base Tape.tail []) Tape.head [])
286
+ Tape.reverseIndex []) Tape.rowIndex (encodeWord (row + 1))
287
+
288
+ def finishInTime (headerPlan plan : Plan) (base : Tape → List Bool)
289
+ (tail head reverse row : Nat)
290
+ (htail : base .tail = encodeWord tail) (hhead : base .head = encodeWord head)
291
+ (hreverse : base .reverseIndex = encodeWord reverse)
292
+ (hrow : base .rowIndex = encodeWord row) (ambient : Ambient) :
293
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
294
+ ⟨some .clearTail, ((ambient, ()), none), base⟩
295
+ (some ⟨some .guard, ((ambient, ()), none), finishTapes base row⟩)
296
+ (tail + head + reverse + 4) := by
297
+ let t₁ := Function.update base Tape.tail []
298
+ let t₂ := Function.update t₁ Tape.head []
299
+ let t₃ := Function.update t₂ Tape.reverseIndex []
300
+ let run₁ := MachineLookup.discardInTime Tape.tail .clearTail .clearHead
301
+ (program headerPlan plan) rfl base tail [] (by simpa using htail) (ambient, ()) none
302
+ have hhead₁ : t₁ .head = encodeWord head := by simp [t₁, hhead]
303
+ let run₂ := MachineLookup.discardInTime Tape.head .clearHead .clearReverse
304
+ (program headerPlan plan) rfl t₁ head [] (by simpa using hhead₁) (ambient, ()) none
305
+ have hreverse₂ : t₂ .reverseIndex = encodeWord reverse := by simp [t₂, t₁, hreverse]
306
+ let run₃ := MachineLookup.discardInTime Tape.reverseIndex .clearReverse .nextRow
307
+ (program headerPlan plan) rfl t₂ reverse [] (by simpa using hreverse₂) (ambient, ()) none
308
+ let run₄ : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
309
+ ⟨some .nextRow, ((ambient, ()), none), t₃⟩
310
+ (some ⟨some .guard, ((ambient, ()), none), finishTapes base row⟩) 1 := {
311
+ steps := 1
312
+ evals_in_steps := by
313
+ change some (TM2.stepAux (program headerPlan plan .nextRow) _ _) = _
314
+ simp only [program, TM2.stepAux]
315
+ congr 2
316
+ simp [t₃, t₂, t₁, finishTapes, hrow, encodeWord, List.replicate_succ]
317
+ steps_le_m := Nat.le_refl _ }
318
+ let r₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ run₂
319
+ let r₁₂₃ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂ run₃
320
+ have run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂₃ run₄
321
+ simpa only [Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] using run
322
+
323
+ end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
324
+
325
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFTableAdapter
326
+
327
+ open PCP
328
+
329
+ def genericRow {n m : Nat} (row : GraphTables.DartRow n m) :
330
+ GenericGraphTables.DartRow 64 n m :=
331
+ ⟨row.tail, row.reverseIndex, row.relation⟩
332
+
333
+ @[simp] theorem genericRow_tail {n m : Nat} (row : GraphTables.DartRow n m) :
334
+ (genericRow row).tail = row.tail := rfl
335
+
336
+ @[simp] theorem genericRow_reverseIndex {n m : Nat} (row : GraphTables.DartRow n m) :
337
+ (genericRow row).reverseIndex = row.reverseIndex := rfl
338
+
339
+ @[simp] theorem genericRow_relation {n m : Nat} (row : GraphTables.DartRow n m) :
340
+ (genericRow row).relation = row.relation := rfl
341
+
342
+ def genericRows {n m : Nat} (rows : GraphTables.Rows n m) :
343
+ GenericGraphTables.Rows 64 n m := rows.map genericRow
344
+
345
+ @[simp] theorem genericRows_get {n m : Nat} (rows : GraphTables.Rows n m) (e : Fin m) :
346
+ (genericRows rows)[e] = genericRow rows[e] := by
347
+ simp [genericRows]
348
+
349
+ @[simp] theorem genericRows_reverseAt {n m : Nat} (rows : GraphTables.Rows n m)
350
+ (e : Fin m) :
351
+ GenericGraphTables.reverseAt (genericRows rows) e = GraphTables.reverseAt rows e := by
352
+ change (genericRows rows)[e].reverseIndex = rows[e].reverseIndex
353
+ rw [genericRows_get]
354
+ rfl
355
+
356
+ @[simp] theorem genericRows_acceptsAt {n m : Nat} (rows : GraphTables.Rows n m)
357
+ (e : Fin m) (a b : Fin 64) :
358
+ GenericGraphTables.acceptsAt (genericRows rows) e a b =
359
+ GraphTables.acceptsAt rows e a b := by
360
+ simp only [GenericGraphTables.acceptsAt, genericRows_get, genericRow_relation]
361
+ rfl
362
+
363
+ theorem genericRows_valid {n m : Nat} (rows : GraphTables.Rows n m)
364
+ (valid : GraphTables.Valid rows) : GenericGraphTables.Valid (genericRows rows) := by
365
+ constructor
366
+ · intro e
367
+ simpa only [genericRows_reverseAt] using valid.1 e
368
+ · intro e a b
369
+ simpa only [genericRows_reverseAt, genericRows_acceptsAt] using valid.2 e a b
370
+
371
+ def genericTable (table : GraphTables.Table) : GenericGraphTables.Table 64 where
372
+ vertices := table.vertices
373
+ darts := table.darts
374
+ rows := genericRows table.rows
375
+ valid := genericRows_valid table.rows table.valid
376
+
377
+ @[simp] theorem genericTable_vertices (table : GraphTables.Table) :
378
+ (genericTable table).vertices = table.vertices := rfl
379
+
380
+ @[simp] theorem genericTable_darts (table : GraphTables.Table) :
381
+ (genericTable table).darts = table.darts := rfl
382
+
383
+ @[simp] theorem genericTable_row (table : GraphTables.Table) (e : Fin table.darts) :
384
+ (genericTable table).rows[e] = genericRow table.rows[e] := genericRows_get _ _
385
+
386
+ @[simp] theorem genericTable_tail (table : GraphTables.Table) (e : Fin table.darts) :
387
+ (genericTable table).rows[e].tail = table.rows[e].tail := by
388
+ rw [genericTable_row]
389
+ rfl
390
+
391
+ @[simp] theorem genericTable_reverseIndex (table : GraphTables.Table) (e : Fin table.darts) :
392
+ (genericTable table).rows[e].reverseIndex = table.rows[e].reverseIndex := by
393
+ rw [genericTable_row]
394
+ rfl
395
+
396
+ @[simp] theorem genericTable_relation (table : GraphTables.Table) (e : Fin table.darts) :
397
+ (genericTable table).rows[e].relation = table.rows[e].relation := by
398
+ rw [genericTable_row]
399
+ rfl
400
+
401
+ @[simp] theorem genericRow_words {n m : Nat} (row : GraphTables.DartRow n m) :
402
+ GenericGraphTables.rowWords (genericRow row) = GraphTables.rowWords row := rfl
403
+
404
+ theorem genericTable_rowList (table : GraphTables.Table) :
405
+ GenericGraphTables.rowList (genericTable table) =
406
+ (GraphTables.rowList table).map genericRow := by
407
+ simp only [GenericGraphTables.rowList, GraphTables.rowList, genericTable,
408
+ genericRows, Vector.toList_map]
409
+
410
+ @[simp] theorem genericTable_tableWords (table : GraphTables.Table) :
411
+ GenericGraphTables.tableWords (genericTable table) = GraphTables.tableWords table := by
412
+ simp only [GenericGraphTables.tableWords, GraphTables.tableWords,
413
+ genericTable_vertices, genericTable_darts, genericTable_rowList, List.flatMap_map,
414
+ genericRow_words]
415
+
416
+ @[simp] theorem genericTable_tableBits (table : GraphTables.Table) :
417
+ GenericGraphTables.tableBits (genericTable table) = GraphTables.tableBits table := by
418
+ simp only [GenericGraphTables.tableBits, GraphTables.tableBits, genericTable_tableWords]
419
+
420
+ @[simp] theorem genericTable_semantics_tail (table : GraphTables.Table) (e : Fin table.darts) :
421
+ (GenericGraphTables.semantics (genericTable table)).tail e =
422
+ (GraphTables.semantics table).tail e := genericTable_tail table e
423
+
424
+ @[simp] theorem genericTable_semantics_reverse (table : GraphTables.Table)
425
+ (e : Fin table.darts) :
426
+ (GenericGraphTables.semantics (genericTable table)).reverse e =
427
+ (GraphTables.semantics table).reverse e := genericTable_reverseIndex table e
428
+
429
+ @[simp] theorem genericTable_semantics_head (table : GraphTables.Table) (e : Fin table.darts) :
430
+ (GenericGraphTables.semantics (genericTable table)).head e =
431
+ (GraphTables.semantics table).head e := by
432
+ simp only [ConstraintGraph.head, genericTable_semantics_reverse, genericTable_semantics_tail]
433
+ rfl
434
+
435
+ @[simp] theorem genericTable_semantics_accepts (table : GraphTables.Table)
436
+ (e : Fin table.darts) (a b : Fin 64) :
437
+ (GenericGraphTables.semantics (genericTable table)).accepts e a b =
438
+ (GraphTables.semantics table).accepts e a b := genericRows_acceptsAt _ _ _ _
439
+
440
+ @[simp] theorem genericTable_headIndex (table : GraphTables.Table) (e : Fin table.darts) :
441
+ AlphabetTable.Lookup.headIndex (genericTable table) e = table.rows[e].reverseIndex :=
442
+ genericTable_reverseIndex table e
443
+
444
+ @[simp] theorem genericTable_headValue (table : GraphTables.Table) (e : Fin table.darts) :
445
+ AlphabetTable.Lookup.headValue (genericTable table) e =
446
+ ((GraphTables.semantics table).head e).val := by
447
+ exact (AlphabetTable.Lookup.headValue_eq_semantics (genericTable table) e).trans
448
+ (congrArg Fin.val (genericTable_semantics_head table e))
449
+
450
+ theorem genericTable_headValue_tableGraph (table : GraphTables.Table) (e : Fin table.darts) :
451
+ AlphabetTable.Lookup.headValue (genericTable table) e =
452
+ ((FinalCNFPattern.tableGraph table).head e).val := by
453
+ rw [genericTable_headValue]
454
+ rfl
455
+
456
+ theorem genericTable_pattern_relation (table : GraphTables.Table) (e : Fin table.darts)
457
+ (p : VerifierToCNF.PatternIndex 12) :
458
+ (genericTable table).rows[e].relation[FinalCNFPattern.patternRelationIndex p] =
459
+ (FinalCNFPattern.tableVerifier table).accepts e (VerifierToCNF.patternAt 12 p) := by
460
+ rw [genericTable_relation]
461
+ exact FinalCNFPattern.pattern_lookup_eq_verifier_accepts table e p
462
+
463
+ end MinUncutGames.Foundations.Complexity.FinalCNFTableAdapter
464
+
465
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
466
+
467
+ open Turing PCP PCP.AlphabetTable FinalCNFTableAdapter
468
+
469
+ @[simp] theorem headRoles_zero : headRoles 0 = Tape.archive := rfl
470
+ @[simp] theorem headRoles_one : headRoles 1 = Tape.reverseIndex := rfl
471
+ @[simp] theorem headRoles_two : headRoles 2 = Tape.scanWork := rfl
472
+ @[simp] theorem headRoles_three : headRoles 3 = Tape.indexWork := rfl
473
+ @[simp] theorem headRoles_four : headRoles 4 = Tape.head := rfl
474
+ @[simp] theorem headRoles_five : headRoles 5 = Tape.scratch := rfl
475
+
476
+ def rowOperands (table : GraphTables.Table) (e : Fin table.darts) : Fin 5 → Nat :=
477
+ values table.vertices table.darts table.rows[e].tail.val
478
+ table.rows[table.rows[e].reverseIndex].tail.val e.val
479
+
480
+ def rowRelation (table : GraphTables.Table) (e : Fin table.darts) : Ambient :=
481
+ ((), fun i => table.rows[e].relation[i])
482
+
483
+ def rowRest (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : List Bool :=
484
+ encodeWords (GraphTables.relationWords table.rows[e].relation) ++ rest
485
+
486
+ def preparedTapes (base : Tape → List Bool) (table : GraphTables.Table)
487
+ (e : Fin table.darts) (rest : List Bool) : Tape → List Bool :=
488
+ Lookup.headLookupTapes headRoles
489
+ (endpointTapes base table.rows[e].tail.val table.rows[e].reverseIndex.val
490
+ (rowRest table e rest)) (genericTable table) e
491
+
492
+ theorem prepared_input (base : Tape → List Bool) (table : GraphTables.Table)
493
+ (e : Fin table.darts) (rest : List Bool) :
494
+ preparedTapes base table e rest .input = rowRest table e rest := by
495
+ simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, endpointTapes,
496
+ Hastad.SourceMachine.fieldTapes]
497
+
498
+ theorem prepared_head (base : Tape → List Bool) (table : GraphTables.Table)
499
+ (e : Fin table.darts) (rest : List Bool) :
500
+ preparedTapes base table e rest .head =
501
+ encodeWord table.rows[table.rows[e].reverseIndex].tail.val := by
502
+ simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes,
503
+ genericTable_headValue, GraphTables.semantics, ConstraintGraph.head,
504
+ GraphTables.reverseAt]
505
+
506
+ theorem prepared_tail (base : Tape → List Bool) (table : GraphTables.Table)
507
+ (e : Fin table.darts) (rest : List Bool) :
508
+ preparedTapes base table e rest .tail = encodeWord table.rows[e].tail.val ++ base .tail := by
509
+ simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, endpointTapes,
510
+ Hastad.SourceMachine.fieldTapes]
511
+
512
+ theorem prepared_reverse (base : Tape → List Bool) (table : GraphTables.Table)
513
+ (e : Fin table.darts) (rest : List Bool) :
514
+ preparedTapes base table e rest .reverseIndex =
515
+ encodeWord table.rows[e].reverseIndex.val ++ base .reverseIndex := by
516
+ simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, endpointTapes,
517
+ Hastad.SourceMachine.fieldTapes]
518
+
519
+ theorem prepared_frame (base : Tape → List Bool) (table : GraphTables.Table)
520
+ (e : Fin table.darts) (rest : List Bool) (tape : Tape)
521
+ (hi : tape ≠ .input) (ht : tape ≠ .tail) (hr : tape ≠ .reverseIndex)
522
+ (hh : tape ≠ .head) (hs : tape ≠ .scanWork) (hx : tape ≠ .indexWork) :
523
+ preparedTapes base table e rest tape = base tape := by
524
+ simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, endpointTapes,
525
+ Hastad.SourceMachine.fieldTapes, hi, ht, hr, hh, hs, hx]
526
+
527
+ def emittedTapes (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table)
528
+ (e : Fin table.darts) (rest : List Bool) : Tape → List Bool :=
529
+ Function.update (Function.update (preparedTapes base table e rest) Tape.input rest)
530
+ Tape.accumulator ((plan.flatMap (Emitter.commandBits (rowOperands table e)
531
+ (rowRelation table e))).reverse ++ base .accumulator)
532
+
533
+ def rowResultTapes (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table)
534
+ (e : Fin table.darts) (rest : List Bool) : Tape → List Bool :=
535
+ finishTapes (emittedTapes plan base table e rest) e.val
536
+
537
+ @[simp] theorem rowResult_input (plan : Plan) (base : Tape → List Bool)
538
+ (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) :
539
+ rowResultTapes plan base table e rest .input = rest := by
540
+ simp [rowResultTapes, finishTapes, emittedTapes]
541
+
542
+ @[simp] theorem rowResult_tail (plan : Plan) (base : Tape → List Bool)
543
+ (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) :
544
+ rowResultTapes plan base table e rest .tail = [] := by
545
+ simp [rowResultTapes, finishTapes]
546
+
547
+ @[simp] theorem rowResult_head (plan : Plan) (base : Tape → List Bool)
548
+ (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) :
549
+ rowResultTapes plan base table e rest .head = [] := by
550
+ simp [rowResultTapes, finishTapes]
551
+
552
+ @[simp] theorem rowResult_reverse (plan : Plan) (base : Tape → List Bool)
553
+ (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) :
554
+ rowResultTapes plan base table e rest .reverseIndex = [] := by
555
+ simp [rowResultTapes, finishTapes]
556
+
557
+ @[simp] theorem rowResult_index (plan : Plan) (base : Tape → List Bool)
558
+ (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) :
559
+ rowResultTapes plan base table e rest .rowIndex = encodeWord (e.val + 1) := by
560
+ simp [rowResultTapes, finishTapes]
561
+
562
+ @[simp] theorem rowResult_accumulator (plan : Plan) (base : Tape → List Bool)
563
+ (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) :
564
+ rowResultTapes plan base table e rest .accumulator =
565
+ (plan.flatMap (Emitter.commandBits (rowOperands table e) (rowRelation table e))).reverse ++
566
+ base .accumulator := by
567
+ simp [rowResultTapes, finishTapes, emittedTapes]
568
+
569
+ theorem rowResult_frame (plan : Plan) (base : Tape → List Bool)
570
+ (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) (tape : Tape)
571
+ (hi : tape ≠ .input) (ht : tape ≠ .tail) (hr : tape ≠ .reverseIndex)
572
+ (hh : tape ≠ .head) (hs : tape ≠ .scanWork) (hx : tape ≠ .indexWork)
573
+ (ha : tape ≠ .accumulator) (hc : tape ≠ .rowIndex) :
574
+ rowResultTapes plan base table e rest tape = base tape := by
575
+ simp only [rowResultTapes, finishTapes, emittedTapes, Function.update_of_ne hi,
576
+ Function.update_of_ne ht, Function.update_of_ne hr, Function.update_of_ne hh,
577
+ Function.update_of_ne ha, Function.update_of_ne hc]
578
+ exact prepared_frame base table e rest tape hi ht hr hh hs hx
579
+
580
+ def guardRowInTime (headerPlan plan : Plan) (base : Tape → List Bool)
581
+ (ambient : Ambient) (hinput : base .input ≠ []) :
582
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
583
+ ⟨some .guard, ((ambient, ()), none), base⟩
584
+ (some ⟨some .startTail, ((ambient, ()), none), base⟩) 1 where
585
+ steps := 1
586
+ evals_in_steps := by
587
+ change some (TM2.stepAux (program headerPlan plan .guard) _ _) = _
588
+ cases hb : base .input with
589
+ | nil => exact False.elim (hinput hb)
590
+ | cons b bs => simp [program, guard, TM2.stepAux, hb]
591
+ steps_le_m := Nat.le_refl _
592
+
593
+ def guardEndInTime (headerPlan plan : Plan) (base : Tape → List Bool)
594
+ (ambient : Ambient) (hinput : base .input = []) :
595
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
596
+ ⟨some .guard, ((ambient, ()), none), base⟩
597
+ (some ⟨some .reverseOutput, ((ambient, ()), none), base⟩) 1 where
598
+ steps := 1
599
+ evals_in_steps := by
600
+ change some (TM2.stepAux (program headerPlan plan .guard) _ _) = _
601
+ simp [program, guard, TM2.stepAux, hinput]
602
+ steps_le_m := Nat.le_refl _
603
+
604
+ theorem prepared_operands (base : Tape → List Bool) (table : GraphTables.Table)
605
+ (e : Fin table.darts) (rest : List Bool)
606
+ (hn : base .vertices = encodeWord table.vertices)
607
+ (hm : base .darts = encodeWord table.darts)
608
+ (hr : base .rowIndex = encodeWord e.val)
609
+ (ht : base .tail = []) :
610
+ ∀ i, (Function.update (preparedTapes base table e rest) Tape.input rest) (source i) =
611
+ encodeWord (rowOperands table e i) := by
612
+ intro i
613
+ fin_cases i
614
+ · simpa [source, rowOperands, values] using
615
+ prepared_frame base table e rest .vertices (by decide) (by decide) (by decide)
616
+ (by decide) (by decide) (by decide) |>.trans hn
617
+ · change (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.darts = _
618
+ simp only [Function.update_of_ne (show Tape.darts ≠ Tape.input by decide)]
619
+ exact (prepared_frame base table e rest .darts (by decide) (by decide) (by decide)
620
+ (by decide) (by decide) (by decide)).trans hm
621
+ · change (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.tail = _
622
+ simp only [Function.update_of_ne (show Tape.tail ≠ Tape.input by decide), prepared_tail,
623
+ ht, List.append_nil]
624
+ rfl
625
+ · change (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.head = _
626
+ simp only [Function.update_of_ne (show Tape.head ≠ Tape.input by decide), prepared_head]
627
+ rfl
628
+ · change (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.rowIndex = _
629
+ simp only [Function.update_of_ne (show Tape.rowIndex ≠ Tape.input by decide)]
630
+ exact (prepared_frame base table e rest .rowIndex (by decide) (by decide) (by decide)
631
+ (by decide) (by decide) (by decide)).trans hr
632
+
633
+ theorem rowOperands_bounded (table : GraphTables.Table) (e : Fin table.darts) :
634
+ ∀ i, rowOperands table e i ≤ (GraphTables.tableBits table).length := by
635
+ intro i
636
+ fin_cases i
637
+ · exact GraphTables.vertices_le_tableBits_length table
638
+ · exact GraphTables.darts_le_tableBits_length table
639
+ · exact table.rows[e].tail.isLt.le.trans (GraphTables.vertices_le_tableBits_length table)
640
+ · exact table.rows[table.rows[e].reverseIndex].tail.isLt.le.trans
641
+ (GraphTables.vertices_le_tableBits_length table)
642
+ · exact e.isLt.le.trans (GraphTables.darts_le_tableBits_length table)
643
+
644
+ def rowTime (plan : Plan) (N : Nat) : Nat :=
645
+ plan.length * (3 * (N + 1) + 3) + 12 * N + 15
646
+
647
+ noncomputable def rowInTime (headerPlan plan : Plan) (base : Tape → List Bool)
648
+ (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool)
649
+ (hinput : base .input = encodeWords (GraphTables.rowWords table.rows[e]) ++ rest)
650
+ (harchive : base .archive = GraphTables.tableBits table)
651
+ (hn : base .vertices = encodeWord table.vertices)
652
+ (hm : base .darts = encodeWord table.darts)
653
+ (hrow : base .rowIndex = encodeWord e.val)
654
+ (ht : base .tail = []) (hh : base .head = []) (hr : base .reverseIndex = [])
655
+ (hscratch : base .scratch = []) (ambient : Ambient) :
656
+ StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
657
+ ⟨some .startTail, ((ambient, ()), none), base⟩
658
+ (some ⟨some .guard, ((rowRelation table e, ()), none),
659
+ rowResultTapes plan base table e rest⟩)
660
+ (rowTime plan (GraphTables.tableBits table).length) := by
661
+ let parsed := endpointTapes base table.rows[e].tail.val table.rows[e].reverseIndex.val
662
+ (rowRest table e rest)
663
+ let ready := preparedTapes base table e rest
664
+ let read := Function.update ready Tape.input rest
665
+ let output := emittedTapes plan base table e rest
666
+ let run₁ := endpointsInTime headerPlan plan base table.rows[e].tail.val
667
+ table.rows[e].reverseIndex.val (rowRest table e rest)
668
+ (by simpa [GraphTables.rowWords, encodeWords, List.append_assoc, rowRest] using hinput) ambient
669
+ have parsed_archive : parsed .archive = GenericGraphTables.tableBits (genericTable table) := by
670
+ simpa [parsed, endpointTapes, Hastad.SourceMachine.fieldTapes] using harchive
671
+ have parsed_reverse : parsed .reverseIndex =
672
+ encodeWord (Lookup.headIndex (genericTable table) e).val := by
673
+ simp [parsed, endpointTapes, Hastad.SourceMachine.fieldTapes, hr]
674
+ have parsed_head : parsed .head = [] := by
675
+ simp [parsed, endpointTapes, Hastad.SourceMachine.fieldTapes, hh]
676
+ have parsed_scratch : parsed .scratch = [] := by
677
+ simp [parsed, endpointTapes, Hastad.SourceMachine.fieldTapes, hscratch]
678
+ let run₂ := headPhaseInTime headerPlan plan parsed (genericTable table) e
679
+ parsed_archive parsed_reverse parsed_head parsed_scratch ambient
680
+ let run₃ := relationInTime headerPlan plan ready table.rows[e].relation rest
681
+ (prepared_input base table e rest) ambient
682
+ have read_operands : ∀ i, read (source i) = encodeWord (rowOperands table e i) :=
683
+ prepared_operands base table e rest hn hm hrow ht
684
+ have read_scratch : read .scratch = [] := by
685
+ simp only [read, Function.update_of_ne (show Tape.scratch ≠ Tape.input by decide)]
686
+ exact (prepared_frame base table e rest .scratch (by decide) (by decide) (by decide)
687
+ (by decide) (by decide) (by decide)).trans hscratch
688
+ have read_acc : read .accumulator = base .accumulator := by
689
+ simp only [read, Function.update_of_ne (show Tape.accumulator ≠ Tape.input by decide)]
690
+ exact prepared_frame base table e rest .accumulator (by decide) (by decide) (by decide)
691
+ (by decide) (by decide) (by decide)
692
+ have run₄ : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
693
+ ⟨some (.row (Emitter.labelAt plan.length 36864 0 .entry)),
694
+ ((rowRelation table e, ()), none), read⟩
695
+ (some ⟨some .clearTail, ((rowRelation table e, ()), none), output⟩)
696
+ (plan.length * (3 * ((GraphTables.tableBits table).length + 1) + 3) + 1) := by
697
+ simpa only [read_acc, output, emittedTapes, read, ready] using
698
+ emitInTime headerPlan plan read (rowOperands table e) read_operands read_scratch
699
+ (rowRelation table e) (GraphTables.tableBits table).length (rowOperands_bounded table e)
700
+ have output_tail : output .tail = encodeWord table.rows[e].tail.val := by
701
+ simp [output, emittedTapes, prepared_tail, ht]
702
+ have output_head : output .head = encodeWord table.rows[table.rows[e].reverseIndex].tail.val := by
703
+ simp [output, emittedTapes, prepared_head]
704
+ have output_reverse : output .reverseIndex = encodeWord table.rows[e].reverseIndex.val := by
705
+ simp [output, emittedTapes, prepared_reverse, hr]
706
+ have output_row : output .rowIndex = encodeWord e.val := by
707
+ simp only [output, emittedTapes,
708
+ Function.update_of_ne (show Tape.rowIndex ≠ Tape.accumulator by decide),
709
+ Function.update_of_ne (show Tape.rowIndex ≠ Tape.input by decide)]
710
+ exact (prepared_frame base table e rest .rowIndex (by decide) (by decide) (by decide)
711
+ (by decide) (by decide) (by decide)).trans hrow
712
+ let run₅ := finishInTime headerPlan plan output table.rows[e].tail.val
713
+ table.rows[table.rows[e].reverseIndex].tail.val table.rows[e].reverseIndex.val e.val
714
+ output_tail output_head output_reverse output_row (rowRelation table e)
715
+ let r₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ run₂
716
+ let r₁₂₃ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂ run₃
717
+ let r₁₂₃₄ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂₃ run₄
718
+ let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂₃₄ run₅
719
+ refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ }
720
+ have hb := run.steps_le_m
721
+ have htbound := rowOperands_bounded table e 2
722
+ have hhbound := rowOperands_bounded table e 3
723
+ have hrbound := table.rows[e].reverseIndex.isLt.le.trans (GraphTables.darts_le_tableBits_length table)
724
+ change table.rows[e].tail.val ≤ _ at htbound
725
+ change table.rows[table.rows[e].reverseIndex].tail.val ≤ _ at hhbound
726
+ simp only [Lookup.headTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul,
727
+ Polynomial.eval_C, Polynomial.eval_X, genericTable_tableBits] at hb
728
+ unfold rowTime
729
+ omega
730
+
731
+ end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
732
+
733
+ end OAI
lean/OAI/Computability/MinUncut/Games/FinalCNFOutput.lean ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.PCP.PoweringFinalConstants
3
+ import OAI.Computability.MinUncut.Games.FinalCNFStream
4
+
5
+ namespace OAI
6
+
7
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
8
+
9
+ open PCP PCP.AlphabetTable
10
+
11
+ def formulaHeader (table : GraphTables.Table) : List Bool :=
12
+ encodeWords [6 * table.vertices + 36864 * table.darts, 40960 * table.darts]
13
+
14
+ theorem formulaHeader_eq (table : GraphTables.Table) :
15
+ formulaHeader table = encodeWords [(FinalTableFormula.output table).«variables»,
16
+ (FinalTableFormula.output table).clauses.length] := by
17
+ simp only [formulaHeader, FinalTableFormula.variable_count, FinalTableFormula.clause_count,
18
+ Nat.mul_comm]
19
+
20
+ theorem headerPlan_eq_formulaHeader (table : GraphTables.Table) (tail head row : Nat)
21
+ (ambient : Ambient) :
22
+ headerPlan.flatMap (Emitter.commandBits
23
+ (values table.vertices table.darts tail head row) ambient) = formulaHeader table :=
24
+ headerPlan_bits table.vertices table.darts tail head row ambient
25
+
26
+ theorem outputStream_eq_clauseBits (table : GraphTables.Table) :
27
+ outputStream rowPlan table (List.finRange table.darts) =
28
+ encodeWords ((FinalTableFormula.output table).clauses.flatMap Complexity.clauseWords) := by
29
+ calc
30
+ _ = (List.finRange table.darts).flatMap (fun e =>
31
+ encodeWords ((VerifierToCNF.eventBlock (FinalCNFPattern.tableVerifier table)
32
+ (by decide) e).flatMap Complexity.clauseWords)) := by
33
+ apply List.flatMap_congr
34
+ intro e he
35
+ exact rowPlan_bits table e
36
+ _ = encodeWords ((List.finRange table.darts).flatMap (fun e =>
37
+ (VerifierToCNF.eventBlock (FinalCNFPattern.tableVerifier table)
38
+ (by decide) e).flatMap Complexity.clauseWords)) :=
39
+ (encodeWords_flatMap _ _).symm
40
+ _ = _ := by
41
+ congr 1
42
+ rw [← List.flatMap_assoc]
43
+ rfl
44
+
45
+ theorem header_append_outputStream (table : GraphTables.Table) :
46
+ formulaHeader table ++ outputStream rowPlan table (List.finRange table.darts) =
47
+ formulaBits (FinalTableFormula.output table) := by
48
+ rw [formulaHeader_eq, outputStream_eq_clauseBits]
49
+ exact (encodeWords_append _ _).symm
50
+
51
+ theorem emitted_output_eq (table : GraphTables.Table) (tail head row : Nat)
52
+ (ambient : Ambient) :
53
+ headerPlan.flatMap (Emitter.commandBits
54
+ (values table.vertices table.darts tail head row) ambient) ++
55
+ outputStream rowPlan table (List.finRange table.darts) =
56
+ formulaBits (FinalTableFormula.output table) := by
57
+ rw [headerPlan_eq_formulaHeader]
58
+ exact header_append_outputStream table
59
+
60
+ theorem reversed_accumulator_output (table : GraphTables.Table) :
61
+ (formulaHeader table ++ outputStream rowPlan table (List.finRange table.darts)).reverse.reverse =
62
+ formulaBits (FinalTableFormula.output table) := by
63
+ rw [List.reverse_reverse, header_append_outputStream]
64
+
65
+ theorem accumulator_length_bound (table : GraphTables.Table) :
66
+ (formulaHeader table ++ outputStream rowPlan table (List.finRange table.darts)).reverse.length ≤
67
+ FinalTableFormula.sizePolynomial.eval (GraphTables.tableBits table).length := by
68
+ rw [List.length_reverse, header_append_outputStream]
69
+ exact FinalTableFormula.formulaBits_length_le_polynomial table
70
+
71
+ open PCP
72
+
73
+ noncomputable def rowTimePolynomial : Polynomial Nat :=
74
+ Polynomial.C 860160 * (Polynomial.C 3 * (Polynomial.X + Polynomial.C 1) + Polynomial.C 3) +
75
+ Polynomial.C 12 * Polynomial.X + Polynomial.C 15
76
+
77
+ theorem rowTimePolynomial_eval (N : Nat) :
78
+ rowTimePolynomial.eval N = rowTime rowPlan N := by
79
+ simp only [rowTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul,
80
+ Polynomial.eval_C, Polynomial.eval_X, rowTime, rowPlan_length]
81
+
82
+ theorem rowTime_expanded (N : Nat) : rowTime rowPlan N = 2580492 * N + 5160975 := by
83
+ rw [rowTime, rowPlan_length]
84
+ omega
85
+
86
+ noncomputable def phaseTimePolynomial : Polynomial Nat :=
87
+ headerTimePolynomial +
88
+ (Polynomial.X * (rowTimePolynomial + Polynomial.C 1) + Polynomial.C 1) +
89
+ (FinalTableFormula.sizePolynomial + Polynomial.C 1)
90
+
91
+ theorem phaseTimePolynomial_eval (N : Nat) :
92
+ phaseTimePolynomial.eval N =
93
+ headerTimePolynomial.eval N + (N * (rowTime rowPlan N + 1) + 1) +
94
+ (FinalTableFormula.sizePolynomial.eval N + 1) := by
95
+ simp only [phaseTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul,
96
+ Polynomial.eval_C, Polynomial.eval_X, rowTimePolynomial_eval]
97
+
98
+ theorem phaseTimePolynomial_eval_expanded (N : Nat) :
99
+ phaseTimePolynomial.eval N = 4532428812 * N ^ 2 + 5484585 * N + 56 := by
100
+ rw [phaseTimePolynomial_eval, headerTimePolynomial_eval, rowTime_expanded,
101
+ FinalTableFormula.sizePolynomial_eval]
102
+ ring
103
+
104
+ theorem phaseTime_le {N rows outputLength : Nat} (rowBound : rows ≤ N)
105
+ (outputBound : outputLength ≤ FinalTableFormula.sizePolynomial.eval N) :
106
+ headerTimePolynomial.eval N + (rows * (rowTime rowPlan N + 1) + 1) +
107
+ (outputLength + 1) ≤ phaseTimePolynomial.eval N := by
108
+ have hrows := Nat.mul_le_mul_right (rowTime rowPlan N + 1) rowBound
109
+ rw [phaseTimePolynomial_eval]
110
+ omega
111
+
112
+ theorem table_phaseTime_le (table : GraphTables.Table) :
113
+ headerTimePolynomial.eval (GraphTables.tableBits table).length +
114
+ (table.darts * (rowTime rowPlan (GraphTables.tableBits table).length + 1) + 1) +
115
+ ((formulaBits (FinalTableFormula.output table)).length + 1) ≤
116
+ phaseTimePolynomial.eval (GraphTables.tableBits table).length :=
117
+ phaseTime_le (GraphTables.darts_le_tableBits_length table)
118
+ (FinalTableFormula.formulaBits_length_le_polynomial table)
119
+
120
+ noncomputable def finalTimePolynomial (C : Nat) : Polynomial Nat :=
121
+ phaseTimePolynomial + Polynomial.C 12 *
122
+ (Polynomial.X + phaseTimePolynomial * Polynomial.C C + Polynomial.C 1) + Polynomial.C 1
123
+
124
+ theorem finalTimePolynomial_eval (C N : Nat) :
125
+ (finalTimePolynomial C).eval N = phaseTimePolynomial.eval N +
126
+ 12 * (N + phaseTimePolynomial.eval N * C + 1) + 1 := by
127
+ simp only [finalTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul,
128
+ Polynomial.eval_C, Polynomial.eval_X]
129
+
130
+ theorem finalTime_le (C N workLength : Nat)
131
+ (workBound : workLength ≤ N + phaseTimePolynomial.eval N * C) :
132
+ phaseTimePolynomial.eval N + 12 * (workLength + 1) + 1 ≤
133
+ (finalTimePolynomial C).eval N := by
134
+ have h := Nat.mul_le_mul_left 12 (Nat.add_le_add_right workBound 1)
135
+ rw [finalTimePolynomial_eval]
136
+ omega
137
+
138
+ end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
139
+
140
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFCleanup
141
+
142
+ open Turing MachineComposition
143
+ open FinalCNFMachine (State)
144
+ open FinalCNFMachine.Program (Tape Plan)
145
+
146
+ section Redirect
147
+
148
+ variable {K Λ Λ' σ : Type} {Γ : K → Type} [DecidableEq K]
149
+
150
+ def redirectLabel (labels : Λ → Λ') (haltTarget : Option Λ') : Option Λ → Option Λ'
151
+ | none => haltTarget
152
+ | some label => some (labels label)
153
+
154
+ def redirectCfg (labels : Λ → Λ') (haltTarget : Option Λ') (cfg : TM2.Cfg Γ Λ σ) :
155
+ TM2.Cfg Γ Λ' σ :=
156
+ ⟨redirectLabel labels haltTarget cfg.l, cfg.var, cfg.stk⟩
157
+
158
+ def redirectStmt (labels : Λ → Λ') (haltTarget : Option Λ') :
159
+ TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ' σ
160
+ | .push k f next => .push k f (redirectStmt labels haltTarget next)
161
+ | .peek k f next => .peek k f (redirectStmt labels haltTarget next)
162
+ | .pop k f next => .pop k f (redirectStmt labels haltTarget next)
163
+ | .load f next => .load f (redirectStmt labels haltTarget next)
164
+ | .branch test yes no => .branch test
165
+ (redirectStmt labels haltTarget yes) (redirectStmt labels haltTarget no)
166
+ | .goto label => .goto (fun state => labels (label state))
167
+ | .halt => match haltTarget with
168
+ | none => .halt
169
+ | some label => .goto (fun _ => label)
170
+
171
+ theorem stepAux_redirect (labels : Λ → Λ') (haltTarget : Option Λ')
172
+ (stmt : TM2.Stmt Γ Λ σ) (state : σ) (tapes : ∀ k, List (Γ k)) :
173
+ TM2.stepAux (redirectStmt labels haltTarget stmt) state tapes =
174
+ redirectCfg labels haltTarget (TM2.stepAux stmt state tapes) := by
175
+ induction stmt generalizing state tapes with
176
+ | push k f next ih => exact ih state (Function.update tapes k (f state :: tapes k))
177
+ | peek k f next ih => exact ih (f state (tapes k).head?) tapes
178
+ | pop k f next ih =>
179
+ exact ih (f state (tapes k).head?) (Function.update tapes k (tapes k).tail)
180
+ | load f next ih => exact ih (f state) tapes
181
+ | branch test yes no ihYes ihNo =>
182
+ cases h : test state with
183
+ | false => simpa only [redirectStmt, TM2.stepAux, h, Bool.cond_false] using ihNo state tapes
184
+ | true => simpa only [redirectStmt, TM2.stepAux, h, Bool.cond_true] using ihYes state tapes
185
+ | goto label => rfl
186
+ | halt => cases haltTarget <;> rfl
187
+
188
+ end Redirect
189
+
190
+ def chosen : List Tape :=
191
+ [.input, .accumulator, .scratch, .vertices, .darts, .tail, .head,
192
+ .rowIndex, .archive, .reverseIndex, .scanWork, .indexWork]
193
+
194
+ @[simp] theorem chosen_length : chosen.length = 12 := rfl
195
+
196
+ @[simp] theorem mem_chosen (tape : Tape) : tape ∈ chosen ↔ tape ≠ .output := by
197
+ cases tape <;> simp [chosen]
198
+
199
+ abbrev Label (headerPlan rowPlan : Plan) :=
200
+ FinalCNFMachine.Program.Label headerPlan.length rowPlan.length ⊕
201
+ (MachineDrainMany.Label chosen ⊕ Unit)
202
+
203
+ def cleanupLabel (headerPlan rowPlan : Plan) : MachineDrainMany.Label chosen → Label headerPlan rowPlan :=
204
+ fun label => .inr (.inl label)
205
+
206
+ def resetLabel (headerPlan rowPlan : Plan) : Label headerPlan rowPlan := .inr (.inr ())
207
+
208
+ def cleanupEntry (headerPlan rowPlan : Plan) : Option (Label headerPlan rowPlan) :=
209
+ MachineDrainMany.entry chosen (cleanupLabel headerPlan rowPlan) (some (resetLabel headerPlan rowPlan))
210
+
211
+ def completedProgram (headerPlan rowPlan : Plan) : Label headerPlan rowPlan →
212
+ TM2.Stmt (fun _ : Tape => Bool) (Label headerPlan rowPlan) (State Unit)
213
+ | .inl label => redirectStmt Sum.inl (cleanupEntry headerPlan rowPlan)
214
+ (FinalCNFMachine.Program.program headerPlan rowPlan label)
215
+ | .inr (.inl label) => MachineDrainMany.instruction chosen (cleanupLabel headerPlan rowPlan)
216
+ (some (resetLabel headerPlan rowPlan)) label
217
+ | .inr (.inr _) => .load (fun _ => (FinalCNFMachine.Program.machine headerPlan rowPlan).initialState) .halt
218
+
219
+ def completedMachine (headerPlan rowPlan : Plan) : FinTM2 where
220
+ K := Tape
221
+ k₀ := .input
222
+ k₁ := .output
223
+ Γ _ := Bool
224
+ Λ := Label headerPlan rowPlan
225
+ main := .inl .copyFirst
226
+ σ := State Unit
227
+ initialState := (FinalCNFMachine.Program.machine headerPlan rowPlan).initialState
228
+ m := completedProgram headerPlan rowPlan
229
+
230
+ def embeddedCfg (headerPlan rowPlan : Plan)
231
+ (cfg : (FinalCNFMachine.Program.machine headerPlan rowPlan).Cfg) :
232
+ (completedMachine headerPlan rowPlan).Cfg :=
233
+ redirectCfg Sum.inl (cleanupEntry headerPlan rowPlan) cfg
234
+
235
+ theorem step_simulation (headerPlan rowPlan : Plan)
236
+ (a b : (FinalCNFMachine.Program.machine headerPlan rowPlan).Cfg)
237
+ (step : (FinalCNFMachine.Program.machine headerPlan rowPlan).step a = some b) :
238
+ (completedMachine headerPlan rowPlan).step (embeddedCfg headerPlan rowPlan a) =
239
+ some (embeddedCfg headerPlan rowPlan b) := by
240
+ cases a with
241
+ | mk label state tapes =>
242
+ cases label with
243
+ | none => simp [FinTM2.step, TM2.step] at step
244
+ | some label =>
245
+ have hb : TM2.stepAux (FinalCNFMachine.Program.program headerPlan rowPlan label)
246
+ state tapes = b := Option.some.inj step
247
+ rw [← hb]
248
+ change some (TM2.stepAux
249
+ (redirectStmt Sum.inl (cleanupEntry headerPlan rowPlan)
250
+ (FinalCNFMachine.Program.program headerPlan rowPlan label)) state tapes) = _
251
+ erw [stepAux_redirect]
252
+ rfl
253
+
254
+ @[simp] theorem embedded_init (headerPlan rowPlan : Plan) (input : List Bool) :
255
+ embeddedCfg headerPlan rowPlan (initList (FinalCNFMachine.Program.machine headerPlan rowPlan) input) =
256
+ initList (completedMachine headerPlan rowPlan) input := rfl
257
+
258
+ theorem finalTapes_eq (base : Tape → List Bool) :
259
+ MachineDrainMany.finalTapes chosen base = MachineDrainMany.haltTapes .output (base .output) := by
260
+ funext tape
261
+ rw [MachineDrainMany.finalTapes_apply]
262
+ simp only [mem_chosen]
263
+ by_cases h : tape = .output
264
+ · subst tape
265
+ simp [MachineDrainMany.haltTapes]
266
+ · simp [MachineDrainMany.haltTapes, h]
267
+
268
+ theorem haltList_eq (headerPlan rowPlan : Plan) (output : List Bool) :
269
+ haltList (completedMachine headerPlan rowPlan) output =
270
+ ⟨none, (FinalCNFMachine.Program.machine headerPlan rowPlan).initialState,
271
+ MachineDrainMany.haltTapes .output output⟩ := by
272
+ congr 1
273
+
274
+ def cleanupExecution (headerPlan rowPlan : Plan) (state : State Unit) (base : Tape → List Bool) :
275
+ StateTransition.EvalsToInTime (completedMachine headerPlan rowPlan).step
276
+ ⟨cleanupEntry headerPlan rowPlan, state, base⟩
277
+ (some (haltList (completedMachine headerPlan rowPlan) (base .output)))
278
+ (MachineDrainMany.steps chosen base + 1) := by
279
+ let after : (completedMachine headerPlan rowPlan).Cfg :=
280
+ ⟨some (resetLabel headerPlan rowPlan),
281
+ (state.1, MachineDrainMany.finalRegister chosen state.2),
282
+ MachineDrainMany.finalTapes chosen base⟩
283
+ have drains : StateTransition.EvalsToInTime (completedMachine headerPlan rowPlan).step
284
+ ⟨cleanupEntry headerPlan rowPlan, state, base⟩ (some after)
285
+ (MachineDrainMany.steps chosen base) := {
286
+ steps := MachineDrainMany.steps chosen base
287
+ evals_in_steps := MachineDrainMany.trace chosen (cleanupLabel headerPlan rowPlan)
288
+ (some (resetLabel headerPlan rowPlan)) (completedProgram headerPlan rowPlan)
289
+ (fun _ => rfl) base state.1 state.2
290
+ steps_le_m := le_rfl }
291
+ have reset : StateTransition.EvalsToInTime (completedMachine headerPlan rowPlan).step
292
+ after (some (haltList (completedMachine headerPlan rowPlan) (base .output))) 1 := {
293
+ steps := 1
294
+ evals_in_steps := by
295
+ change some (⟨none, (FinalCNFMachine.Program.machine headerPlan rowPlan).initialState,
296
+ MachineDrainMany.finalTapes chosen base⟩ : (completedMachine headerPlan rowPlan).Cfg) =
297
+ some (haltList (completedMachine headerPlan rowPlan) (base .output))
298
+ erw [finalTapes_eq, haltList_eq]
299
+ rfl
300
+ steps_le_m := le_rfl }
301
+ simpa only [Nat.add_comm] using
302
+ StateTransition.EvalsToInTime.trans _ (MachineDrainMany.steps chosen base) 1
303
+ _ after _ drains reset
304
+
305
+ def outputsInTime (headerPlan rowPlan : Plan) (input output : List Bool)
306
+ (state : State Unit) (base : Tape → List Bool) (budget : Nat)
307
+ (raw : StateTransition.EvalsToInTime
308
+ (FinalCNFMachine.Program.machine headerPlan rowPlan).step
309
+ (initList (FinalCNFMachine.Program.machine headerPlan rowPlan) input)
310
+ (some ⟨none, state, base⟩) budget)
311
+ (correctOutput : base .output = output) :
312
+ TM2OutputsInTime (completedMachine headerPlan rowPlan) input (some output)
313
+ (budget + 12 * (input.length + budget *
314
+ Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan) + 1) + 1) := by
315
+ let lifted := liftExecutionInTime
316
+ (FinalCNFMachine.Program.machine headerPlan rowPlan).step
317
+ (completedMachine headerPlan rowPlan).step (embeddedCfg headerPlan rowPlan)
318
+ (step_simulation headerPlan rowPlan) raw
319
+ have joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ lifted
320
+ (cleanupExecution headerPlan rowPlan state base)
321
+ have stackBound : ∀ tape, (base tape).length ≤ input.length + budget *
322
+ Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan) := by
323
+ intro tape
324
+ have h := Runtime.executionSizeBound
325
+ (FinalCNFMachine.Program.machine headerPlan rowPlan).step
326
+ (fun cfg => (cfg.stk tape).length)
327
+ (Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan))
328
+ (Runtime.stepStackLength (FinalCNFMachine.Program.machine headerPlan rowPlan) tape) raw
329
+ exact h.trans (Nat.add_le_add_right
330
+ (Runtime.initialStackLength (FinalCNFMachine.Program.machine headerPlan rowPlan) input tape) _)
331
+ have cleanupBound := MachineDrainMany.steps_le_uniform chosen base _ stackBound
332
+ rw [chosen_length] at cleanupBound
333
+ rw [embedded_init, correctOutput] at joined
334
+ exact { toEvalsTo := joined.toEvalsTo
335
+ steps_le_m := joined.steps_le_m.trans (by omega) }
336
+
337
+ noncomputable def completedTime (headerPlan rowPlan : Plan) (rawTime : Polynomial Nat) : Polynomial Nat :=
338
+ rawTime + Polynomial.C 12 * (Polynomial.X + rawTime *
339
+ Polynomial.C (Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan)) + 1) + 1
340
+
341
+ theorem completedTime_eval (headerPlan rowPlan : Plan) (rawTime : Polynomial Nat) (n : Nat) :
342
+ (completedTime headerPlan rowPlan rawTime).eval n =
343
+ rawTime.eval n + 12 * (n + rawTime.eval n *
344
+ Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan) + 1) + 1 := by
345
+ simp [completedTime]
346
+
347
+ end MinUncutGames.Foundations.Complexity.FinalCNFCleanup
348
+
349
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
350
+
351
+ open Turing PCP
352
+
353
+ theorem emittedBytes_eq_formulaBits (table : GraphTables.Table) :
354
+ emittedBytes rowPlan table = formulaBits (FinalTableFormula.output table) :=
355
+ header_append_outputStream table
356
+
357
+ theorem rawBudget_le_phaseTime (table : GraphTables.Table) :
358
+ rawBudget rowPlan table ≤ phaseTimePolynomial.eval (GraphTables.tableBits table).length := by
359
+ unfold rawBudget
360
+ rw [emittedBytes_eq_formulaBits]
361
+ simpa only [Nat.add_assoc] using table_phaseTime_le table
362
+
363
+ noncomputable def computableInPolyTime :
364
+ TM2ComputableInPolyTime GraphTables.tableBits formulaBits FinalTableFormula.output where
365
+ tm := FinalCNFCleanup.completedMachine headerPlan rowPlan
366
+ inputAlphabet := Equiv.refl Bool
367
+ outputAlphabet := Equiv.refl Bool
368
+ time := finalTimePolynomial (Runtime.programPushBound (machine headerPlan rowPlan))
369
+ outputsFun table := by
370
+ change TM2OutputsInTime (FinalCNFCleanup.completedMachine headerPlan rowPlan)
371
+ ((GraphTables.tableBits table).map id)
372
+ (some ((formulaBits (FinalTableFormula.output table)).map id))
373
+ ((finalTimePolynomial (Runtime.programPushBound (machine headerPlan rowPlan))).eval
374
+ (GraphTables.tableBits table).length)
375
+ have input_eq : @List.map
376
+ ((FinalCNFCleanup.completedMachine headerPlan rowPlan).Γ
377
+ (FinalCNFCleanup.completedMachine headerPlan rowPlan).k₀)
378
+ ((FinalCNFCleanup.completedMachine headerPlan rowPlan).Γ
379
+ (FinalCNFCleanup.completedMachine headerPlan rowPlan).k₀)
380
+ id (GraphTables.tableBits table) = GraphTables.tableBits table := List.map_id _
381
+ have output_eq : @List.map
382
+ ((FinalCNFCleanup.completedMachine headerPlan rowPlan).Γ
383
+ (FinalCNFCleanup.completedMachine headerPlan rowPlan).k₁)
384
+ ((FinalCNFCleanup.completedMachine headerPlan rowPlan).Γ
385
+ (FinalCNFCleanup.completedMachine headerPlan rowPlan).k₁)
386
+ id (formulaBits (FinalTableFormula.output table)) =
387
+ formulaBits (FinalTableFormula.output table) := List.map_id _
388
+ rw [input_eq, output_eq, finalTimePolynomial_eval]
389
+ let raw := rawRun rowPlan table
390
+ let bounded : StateTransition.EvalsToInTime (machine headerPlan rowPlan).step
391
+ (initList (machine headerPlan rowPlan) (GraphTables.tableBits table))
392
+ (some ⟨none, ((raw.finalAmbient, ()), none), raw.finalTapes⟩)
393
+ (phaseTimePolynomial.eval (GraphTables.tableBits table).length) := {
394
+ toEvalsTo := raw.execution.toEvalsTo
395
+ steps_le_m := raw.execution.steps_le_m.trans (rawBudget_le_phaseTime table) }
396
+ have correct : raw.finalTapes .output = formulaBits (FinalTableFormula.output table) :=
397
+ raw.output.trans (emittedBytes_eq_formulaBits table)
398
+ have run := FinalCNFCleanup.outputsInTime headerPlan rowPlan
399
+ (GraphTables.tableBits table) (formulaBits (FinalTableFormula.output table))
400
+ ((raw.finalAmbient, ()), none) raw.finalTapes
401
+ (phaseTimePolynomial.eval (GraphTables.tableBits table).length) bounded correct
402
+ exact run
403
+
404
+ end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
405
+
406
+ end OAI
lean/OAI/Computability/MinUncut/Games/FinalCNFPattern.lean ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.PCP.FinalBooleanVerifier
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFPattern
8
+
9
+ open PCP
10
+ open scoped BigOperators
11
+
12
+ abbrev Label := FinalBooleanVerifier.Label
13
+
14
+ abbrev labelEquiv : Label ≃ Fin 64 := AlphabetTable.Enumeration.labelEquiv
15
+
16
+ theorem labelEquiv_val (label : Label) :
17
+ (labelEquiv label).val =
18
+ ∑ i : Fin 6, AlphabetTable.Enumeration.bitValue (label i) * 2 ^ i.val :=
19
+ AlphabetTable.Enumeration.labelEquiv_val label
20
+
21
+ def labelIndex (label : Label) : Fin 64 := labelEquiv label
22
+
23
+ def labelBits (index : Fin 64) : Label := labelEquiv.symm index
24
+
25
+ @[simp] theorem labelBits_labelIndex (label : Label) :
26
+ labelBits (labelIndex label) = label := labelEquiv.symm_apply_apply label
27
+
28
+ @[simp] theorem labelIndex_labelBits (index : Fin 64) :
29
+ labelIndex (labelBits index) = index := labelEquiv.apply_symm_apply index
30
+
31
+ def leftHalf (bits : VerifierToCNF.Pattern 12) : Label :=
32
+ fun j => bits (Fin.castAdd 6 j)
33
+
34
+ def rightHalf (bits : VerifierToCNF.Pattern 12) : Label :=
35
+ fun j => bits (Fin.natAdd 6 j)
36
+
37
+ def relationAddress (bits : VerifierToCNF.Pattern 12) : Fin 4096 :=
38
+ GraphTables.relationIndex (labelIndex (leftHalf bits), labelIndex (rightHalf bits))
39
+
40
+ theorem relationAddress_val (bits : VerifierToCNF.Pattern 12) :
41
+ (relationAddress bits).val =
42
+ 64 * (labelIndex (leftHalf bits)).val + (labelIndex (rightHalf bits)).val := by
43
+ rw [relationAddress, GraphTables.relationIndex_val, Nat.add_comm]
44
+
45
+ def patternRelationIndex (p : VerifierToCNF.PatternIndex 12) : Fin 4096 :=
46
+ relationAddress (VerifierToCNF.patternAt 12 p)
47
+
48
+ @[simp] theorem patternRelationIndex_eq (p : VerifierToCNF.PatternIndex 12) :
49
+ patternRelationIndex p = relationAddress (VerifierToCNF.patternAt 12 p) := rfl
50
+
51
+ def tableGraph (table : GraphTables.Table) :
52
+ ConstraintGraph (Fin table.vertices) (Fin table.darts) Label :=
53
+ (GraphTables.semantics table).reindex (Equiv.refl _) (Equiv.refl _) labelEquiv.symm
54
+
55
+ @[simp] theorem tableGraph_tail (table : GraphTables.Table) (e : Fin table.darts) :
56
+ (tableGraph table).tail e = table.rows[e].tail := rfl
57
+
58
+ @[simp] theorem tableGraph_reverse (table : GraphTables.Table) (e : Fin table.darts) :
59
+ (tableGraph table).reverse e = table.rows[e].reverseIndex := rfl
60
+
61
+ @[simp] theorem tableGraph_accepts (table : GraphTables.Table) (e : Fin table.darts)
62
+ (a b : Label) :
63
+ (tableGraph table).accepts e a b =
64
+ GraphTables.relationAt table.rows[e].relation (labelIndex a) (labelIndex b) := rfl
65
+
66
+ abbrev tableVerifier (table : GraphTables.Table) : VerifierToCNF.FiniteVerifier 12 :=
67
+ FinalBooleanVerifier.verifier (tableGraph table) (Equiv.refl _) (Equiv.refl _)
68
+
69
+ theorem relation_lookup_eq_verifier_accepts (table : GraphTables.Table)
70
+ (e : Fin table.darts) (bits : VerifierToCNF.Pattern 12) :
71
+ table.rows[e].relation[relationAddress bits] =
72
+ (tableVerifier table).accepts e bits := rfl
73
+
74
+ theorem pattern_lookup_eq_verifier_accepts (table : GraphTables.Table)
75
+ (e : Fin table.darts) (p : VerifierToCNF.PatternIndex 12) :
76
+ table.rows[e].relation[patternRelationIndex p] =
77
+ (tableVerifier table).accepts e (VerifierToCNF.patternAt 12 p) := rfl
78
+
79
+ theorem verifier_accepts_eq_lookup (table : GraphTables.Table)
80
+ (e : Fin table.darts) (bits : VerifierToCNF.Pattern 12) :
81
+ (tableVerifier table).accepts e bits =
82
+ table.rows[e].relation[relationAddress bits] := rfl
83
+
84
+ theorem buffer_lookup_eq_verifier_accepts (table : GraphTables.Table)
85
+ (e : Fin table.darts) (buffer : Fin 4096 → Bool)
86
+ (read_correct : ∀ i, buffer i = table.rows[e].relation[i])
87
+ (bits : VerifierToCNF.Pattern 12) :
88
+ buffer (relationAddress bits) = (tableVerifier table).accepts e bits :=
89
+ (read_correct _).trans (relation_lookup_eq_verifier_accepts table e bits)
90
+
91
+ theorem pattern_buffer_lookup_eq_verifier_accepts (table : GraphTables.Table)
92
+ (e : Fin table.darts) (buffer : Fin 4096 → Bool)
93
+ (read_correct : ∀ i, buffer i = table.rows[e].relation[i])
94
+ (p : VerifierToCNF.PatternIndex 12) :
95
+ buffer (patternRelationIndex p) =
96
+ (tableVerifier table).accepts e (VerifierToCNF.patternAt 12 p) :=
97
+ buffer_lookup_eq_verifier_accepts table e buffer read_correct _
98
+
99
+ end MinUncutGames.Foundations.Complexity.FinalCNFPattern
100
+
101
+ end
102
+
103
+ end OAI
lean/OAI/Computability/MinUncut/Games/FinalCNFStream.lean ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.FinalCNFHeader
3
+
4
+ namespace OAI
5
+
6
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
7
+
8
+ open PCP PCP.AlphabetTable FinalCNFTableAdapter
9
+
10
+ def remainingEvents (table : GraphTables.Table) (r : Nat) : List (Fin table.darts) :=
11
+ (List.finRange table.darts).drop r
12
+
13
+ def processedEvents (table : GraphTables.Table) (r : Nat) : List (Fin table.darts) :=
14
+ (List.finRange table.darts).take r
15
+
16
+ def inputStream (table : GraphTables.Table) (events : List (Fin table.darts)) : List Bool :=
17
+ events.flatMap (fun e => encodeWords (GraphTables.rowWords table.rows[e]))
18
+
19
+ def outputStream (plan : Plan) (table : GraphTables.Table)
20
+ (events : List (Fin table.darts)) : List Bool :=
21
+ events.flatMap (fun e => plan.flatMap (Emitter.commandBits (rowOperands table e)
22
+ (rowRelation table e)))
23
+
24
+ @[simp] theorem remainingEvents_zero (table : GraphTables.Table) :
25
+ remainingEvents table 0 = List.finRange table.darts := by
26
+ simp [remainingEvents]
27
+
28
+ @[simp] theorem remainingEvents_length (table : GraphTables.Table) (r : Nat) :
29
+ (remainingEvents table r).length = table.darts - r := by
30
+ simp [remainingEvents]
31
+
32
+ @[simp] theorem remainingEvents_done (table : GraphTables.Table) :
33
+ remainingEvents table table.darts = [] := by
34
+ simp [remainingEvents]
35
+
36
+ theorem remainingEvents_cons (table : GraphTables.Table) (r : Nat) (h : r < table.darts) :
37
+ remainingEvents table r = ⟨r, h⟩ :: remainingEvents table (r + 1) := by
38
+ unfold remainingEvents
39
+ rw [List.drop_eq_getElem_cons (l := List.finRange table.darts) (i := r)
40
+ (by simpa using h)]
41
+ simp
42
+
43
+ @[simp] theorem processedEvents_zero (table : GraphTables.Table) :
44
+ processedEvents table 0 = [] := by simp [processedEvents]
45
+
46
+ @[simp] theorem processedEvents_done (table : GraphTables.Table) :
47
+ processedEvents table table.darts = List.finRange table.darts := by
48
+ simp [processedEvents]
49
+
50
+ theorem processedEvents_succ (table : GraphTables.Table) (r : Nat) (h : r < table.darts) :
51
+ processedEvents table (r + 1) = processedEvents table r ++ [⟨r, h⟩] := by
52
+ unfold processedEvents
53
+ rw [List.take_succ_eq_append_getElem (l := List.finRange table.darts) (i := r)
54
+ (by simpa using h)]
55
+ simp
56
+
57
+ theorem processed_append_remaining (table : GraphTables.Table) (r : Nat) :
58
+ processedEvents table r ++ remainingEvents table r = List.finRange table.darts := by
59
+ exact List.take_append_drop r (List.finRange table.darts)
60
+
61
+ @[simp] theorem inputStream_nil (table : GraphTables.Table) : inputStream table [] = [] := rfl
62
+
63
+ @[simp] theorem inputStream_cons (table : GraphTables.Table) (e : Fin table.darts)
64
+ (events : List (Fin table.darts)) :
65
+ inputStream table (e :: events) =
66
+ encodeWords (GraphTables.rowWords table.rows[e]) ++ inputStream table events := rfl
67
+
68
+ @[simp] theorem inputStream_append (table : GraphTables.Table)
69
+ (first rest : List (Fin table.darts)) :
70
+ inputStream table (first ++ rest) = inputStream table first ++ inputStream table rest := by
71
+ simp only [inputStream, List.flatMap_append]
72
+
73
+ @[simp] theorem outputStream_nil (plan : Plan) (table : GraphTables.Table) :
74
+ outputStream plan table [] = [] := rfl
75
+
76
+ @[simp] theorem outputStream_cons (plan : Plan) (table : GraphTables.Table)
77
+ (e : Fin table.darts) (events : List (Fin table.darts)) :
78
+ outputStream plan table (e :: events) =
79
+ plan.flatMap (Emitter.commandBits (rowOperands table e) (rowRelation table e)) ++
80
+ outputStream plan table events := rfl
81
+
82
+ @[simp] theorem outputStream_append (plan : Plan) (table : GraphTables.Table)
83
+ (first rest : List (Fin table.darts)) :
84
+ outputStream plan table (first ++ rest) =
85
+ outputStream plan table first ++ outputStream plan table rest := by
86
+ simp only [outputStream, List.flatMap_append]
87
+
88
+ theorem inputStream_remaining_cons (table : GraphTables.Table) (r : Nat)
89
+ (h : r < table.darts) :
90
+ inputStream table (remainingEvents table r) =
91
+ encodeWords (GraphTables.rowWords table.rows[(⟨r, h⟩ : Fin table.darts)]) ++
92
+ inputStream table (remainingEvents table (r + 1)) := by
93
+ rw [remainingEvents_cons table r h, inputStream_cons]
94
+
95
+ theorem outputStream_remaining_cons (plan : Plan) (table : GraphTables.Table) (r : Nat)
96
+ (h : r < table.darts) :
97
+ outputStream plan table (remainingEvents table r) =
98
+ plan.flatMap (Emitter.commandBits (rowOperands table ⟨r, h⟩)
99
+ (rowRelation table ⟨r, h⟩)) ++
100
+ outputStream plan table (remainingEvents table (r + 1)) := by
101
+ rw [remainingEvents_cons table r h, outputStream_cons]
102
+
103
+ theorem outputStream_processed_succ (plan : Plan) (table : GraphTables.Table) (r : Nat)
104
+ (h : r < table.darts) :
105
+ outputStream plan table (processedEvents table (r + 1)) =
106
+ outputStream plan table (processedEvents table r) ++
107
+ plan.flatMap (Emitter.commandBits (rowOperands table ⟨r, h⟩)
108
+ (rowRelation table ⟨r, h⟩)) := by
109
+ rw [processedEvents_succ table r h, outputStream_append]
110
+ simp
111
+
112
+ theorem inputStream_split (table : GraphTables.Table) (r : Nat) :
113
+ inputStream table (List.finRange table.darts) =
114
+ inputStream table (processedEvents table r) ++
115
+ inputStream table (remainingEvents table r) := by
116
+ rw [← inputStream_append, processed_append_remaining]
117
+
118
+ theorem outputStream_split (plan : Plan) (table : GraphTables.Table) (r : Nat) :
119
+ outputStream plan table (List.finRange table.darts) =
120
+ outputStream plan table (processedEvents table r) ++
121
+ outputStream plan table (remainingEvents table r) := by
122
+ rw [← outputStream_append, processed_append_remaining]
123
+
124
+ private theorem encodeWords_flatMap_rows {α : Type} (rows : List α) (words : α → List Nat) :
125
+ encodeWords (rows.flatMap words) = rows.flatMap (fun row => encodeWords (words row)) := by
126
+ induction rows with
127
+ | nil => rfl
128
+ | cons row rows ih => simp only [List.flatMap_cons, encodeWords_append, ih]
129
+
130
+ theorem rowList_eq_finRange_map (table : GraphTables.Table) :
131
+ GraphTables.rowList table = (List.finRange table.darts).map (fun e => table.rows[e]) := by
132
+ rw [← List.ofFn_eq_map, ← Vector.toList_ofFn]
133
+ change table.rows.toList = (Vector.ofFn (fun i => table.rows[i.val])).toList
134
+ rw [Vector.ofFn_getElem]
135
+
136
+ theorem inputStream_all (table : GraphTables.Table) :
137
+ inputStream table (List.finRange table.darts) = tableRowsBits (genericTable table) := by
138
+ rw [tableRowsBits, genericTable_rowList]
139
+ change inputStream table (List.finRange table.darts) =
140
+ encodeWords (((GraphTables.rowList table).map genericRow).flatMap
141
+ (fun row : GenericGraphTables.DartRow 64 table.vertices table.darts =>
142
+ GenericGraphTables.rowWords row))
143
+ rw [List.flatMap_map]
144
+ simp only [genericRow_words]
145
+ rw [rowList_eq_finRange_map, List.flatMap_map, encodeWords_flatMap_rows]
146
+ rfl
147
+
148
+ theorem inputStream_remaining_zero (table : GraphTables.Table) :
149
+ inputStream table (remainingEvents table 0) = tableRowsBits (genericTable table) := by
150
+ rw [remainingEvents_zero, inputStream_all]
151
+
152
+ theorem outputStream_accumulator_succ (plan : Plan) (table : GraphTables.Table)
153
+ (r : Nat) (h : r < table.darts) (header : List Bool) :
154
+ (plan.flatMap (Emitter.commandBits (rowOperands table ⟨r, h⟩)
155
+ (rowRelation table ⟨r, h⟩))).reverse ++
156
+ (header ++ outputStream plan table (processedEvents table r)).reverse =
157
+ (header ++ outputStream plan table (processedEvents table (r + 1))).reverse := by
158
+ rw [outputStream_processed_succ plan table r h]
159
+ simp only [List.reverse_append, List.append_assoc]
160
+
161
+ open Turing PCP PCP.AlphabetTable
162
+
163
+ structure LoopInvariant (table : GraphTables.Table) (r : Nat) (base : Tape → List Bool) : Prop where
164
+ input : base .input = inputStream table (remainingEvents table r)
165
+ archive : base .archive = GraphTables.tableBits table
166
+ vertices : base .vertices = encodeWord table.vertices
167
+ darts : base .darts = encodeWord table.darts
168
+ index : base .rowIndex = encodeWord r
169
+ tail : base .tail = []
170
+ head : base .head = []
171
+ reverse : base .reverseIndex = []
172
+ scratch : base .scratch = []
173
+
174
+ structure LoopRun (headerPlan plan : Plan) (table : GraphTables.Table) (r remaining : Nat)
175
+ (base : Tape → List Bool) (ambient : Ambient) where
176
+ finalAmbient : Ambient
177
+ finalTapes : Tape → List Bool
178
+ execution : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan))
179
+ ⟨some .guard, ((ambient, ()), none), base⟩
180
+ (some ⟨some .reverseOutput, ((finalAmbient, ()), none), finalTapes⟩)
181
+ (remaining * (rowTime plan (GraphTables.tableBits table).length + 1) + 1)
182
+ accumulator : finalTapes .accumulator =
183
+ (outputStream plan table (remainingEvents table r)).reverse ++ base .accumulator
184
+ output : finalTapes .output = base .output
185
+
186
+ theorem rowInvariant_succ (plan : Plan) (table : GraphTables.Table) (r : Nat)
187
+ (hr : r < table.darts) (base : Tape → List Bool) (invariant : LoopInvariant table r base) :
188
+ LoopInvariant table (r + 1)
189
+ (rowResultTapes plan base table ⟨r, hr⟩
190
+ (inputStream table (remainingEvents table (r + 1)))) := by
191
+ constructor
192
+ · exact rowResult_input _ _ _ _ _
193
+ · exact (rowResult_frame _ _ _ _ _ .archive (by decide) (by decide) (by decide)
194
+ (by decide) (by decide) (by decide) (by decide) (by decide)).trans invariant.archive
195
+ · exact (rowResult_frame _ _ _ _ _ .vertices (by decide) (by decide) (by decide)
196
+ (by decide) (by decide) (by decide) (by decide) (by decide)).trans invariant.vertices
197
+ · exact (rowResult_frame _ _ _ _ _ .darts (by decide) (by decide) (by decide)
198
+ (by decide) (by decide) (by decide) (by decide) (by decide)).trans invariant.darts
199
+ · exact rowResult_index _ _ _ _ _
200
+ · exact rowResult_tail _ _ _ _ _
201
+ · exact rowResult_head _ _ _ _ _
202
+ · exact rowResult_reverse _ _ _ _ _
203
+ · exact (rowResult_frame _ _ _ _ _ .scratch (by decide) (by decide) (by decide)
204
+ (by decide) (by decide) (by decide) (by decide) (by decide)).trans invariant.scratch
205
+
206
+ theorem rowWords_nonempty (table : GraphTables.Table) (e : Fin table.darts) :
207
+ encodeWords (GraphTables.rowWords table.rows[e]) ≠ [] := by
208
+ simp [GraphTables.rowWords, encodeWords, encodeWord]
209
+
210
+ noncomputable def loopInTime (headerPlan plan : Plan) (table : GraphTables.Table)
211
+ (remaining : Nat) :
212
+ ∀ (r : Nat) (_ : r + remaining = table.darts) (base : Tape → List Bool)
213
+ (ambient : Ambient), LoopInvariant table r base →
214
+ LoopRun headerPlan plan table r remaining base ambient := by
215
+ induction remaining with
216
+ | zero =>
217
+ intro r hcount base ambient invariant
218
+ have hr : r = table.darts := by omega
219
+ have hinput : base .input = [] := by
220
+ simpa only [hr, remainingEvents_done, inputStream_nil] using invariant.input
221
+ refine {
222
+ finalAmbient := ambient
223
+ finalTapes := base
224
+ execution := ?_
225
+ accumulator := ?_
226
+ output := rfl }
227
+ · simpa only [Nat.zero_mul, Nat.zero_add] using
228
+ guardEndInTime headerPlan plan base ambient hinput
229
+ · simp only [hr, remainingEvents_done, outputStream_nil, List.reverse_nil, List.nil_append]
230
+ | succ remaining ih =>
231
+ intro r hcount base ambient invariant
232
+ have hr : r < table.darts := by omega
233
+ let e : Fin table.darts := ⟨r, hr⟩
234
+ let rest := inputStream table (remainingEvents table (r + 1))
235
+ let next := rowResultTapes plan base table e rest
236
+ have hinput : base .input = encodeWords (GraphTables.rowWords table.rows[e]) ++ rest := by
237
+ rw [invariant.input, inputStream_remaining_cons table r hr]
238
+ have hnonempty : base .input ≠ [] := by
239
+ rw [hinput]
240
+ exact List.append_ne_nil_of_left_ne_nil (rowWords_nonempty table e) rest
241
+ let guardRun := guardRowInTime headerPlan plan base ambient hnonempty
242
+ let rowRun := rowInTime headerPlan plan base table e rest hinput invariant.archive
243
+ invariant.vertices invariant.darts invariant.index invariant.tail invariant.head
244
+ invariant.reverse invariant.scratch ambient
245
+ let first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ guardRun rowRun
246
+ let later := ih (r + 1) (by omega) next (rowRelation table e)
247
+ (rowInvariant_succ plan table r hr base invariant)
248
+ let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first later.execution
249
+ refine {
250
+ finalAmbient := later.finalAmbient
251
+ finalTapes := later.finalTapes
252
+ execution := { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ }
253
+ accumulator := ?_
254
+ output := ?_ }
255
+ · have hb := run.steps_le_m
256
+ rw [Nat.succ_mul]
257
+ omega
258
+ · rw [later.accumulator, outputStream_remaining_cons plan table r hr]
259
+ simp only [next, rowResult_accumulator, List.reverse_append, List.append_assoc]
260
+ rfl
261
+ · rw [later.output]
262
+ exact rowResult_frame _ _ _ _ _ .output (by decide) (by decide) (by decide)
263
+ (by decide) (by decide) (by decide) (by decide) (by decide)
264
+
265
+ open Turing PCP PCP.AlphabetTable FinalCNFTableAdapter
266
+
267
+ def emittedBytes (plan : Plan) (table : GraphTables.Table) : List Bool :=
268
+ encodeWords [6 * table.vertices + 36864 * table.darts, 40960 * table.darts] ++
269
+ outputStream plan table (List.finRange table.darts)
270
+
271
+ noncomputable def rawBudget (plan : Plan) (table : GraphTables.Table) : Nat :=
272
+ headerTimePolynomial.eval (GraphTables.tableBits table).length +
273
+ table.darts * (rowTime plan (GraphTables.tableBits table).length + 1) + 1 +
274
+ (emittedBytes plan table).length + 1
275
+
276
+ structure RawRun (plan : Plan) (table : GraphTables.Table) where
277
+ finalAmbient : Ambient
278
+ finalTapes : Tape → List Bool
279
+ execution : StateTransition.EvalsToInTime (machine headerPlan plan).step
280
+ (initList (machine headerPlan plan) (GraphTables.tableBits table))
281
+ (some ⟨none, ((finalAmbient, ()), none), finalTapes⟩) (rawBudget plan table)
282
+ output : finalTapes .output = emittedBytes plan table
283
+
284
+ theorem header_loopInvariant (_ : Plan) (table : GraphTables.Table) :
285
+ LoopInvariant table 0 (headerResultTapes table.vertices table.darts
286
+ (tableRowsBits (genericTable table))) := by
287
+ constructor
288
+ · rw [headerResultTapes_input, inputStream_remaining_zero]
289
+ · rw [headerResultTapes_archive]
290
+ exact (tableBits_header_rows (genericTable table)).symm.trans (genericTable_tableBits table)
291
+ · rfl
292
+ · rfl
293
+ · exact headerResultTapes_rowIndex _ _ _
294
+ · rfl
295
+ · rfl
296
+ · rfl
297
+ · rfl
298
+
299
+ noncomputable def rawRun (plan : Plan) (table : GraphTables.Table) : RawRun plan table := by
300
+ let base := headerResultTapes table.vertices table.darts (tableRowsBits (genericTable table))
301
+ let ambient : Ambient := ((), fun _ => false)
302
+ have headerRun : StateTransition.EvalsToInTime (machine headerPlan plan).step
303
+ (initList (machine headerPlan plan) (GraphTables.tableBits table))
304
+ (some ⟨some .guard, ((ambient, ()), none), base⟩)
305
+ (headerTimePolynomial.eval (GraphTables.tableBits table).length) := by
306
+ simpa only [genericTable_tableBits, genericTable_vertices, genericTable_darts, base, ambient]
307
+ using initializedTableHeaderInTime plan (genericTable table)
308
+ let loop := loopInTime headerPlan plan table table.darts 0 (by omega)
309
+ base ambient (header_loopInvariant plan table)
310
+ have acc : loop.finalTapes .accumulator = (emittedBytes plan table).reverse := by
311
+ rw [loop.accumulator]
312
+ simp only [remainingEvents_zero, base, headerResultTapes_accumulator, emittedBytes,
313
+ List.reverse_append]
314
+ have out : loop.finalTapes .output = [] := by
315
+ rw [loop.output]
316
+ rfl
317
+ let finalTapes := Reduction.MachineTransfer.tapesAt Tape.accumulator Tape.output
318
+ loop.finalTapes [] (emittedBytes plan table)
319
+ have finish : StateTransition.EvalsToInTime (machine headerPlan plan).step
320
+ ⟨some .reverseOutput, ((loop.finalAmbient, ()), none), loop.finalTapes⟩
321
+ (some ⟨none, ((loop.finalAmbient, ()), none), finalTapes⟩)
322
+ ((emittedBytes plan table).length + 1) := by
323
+ have run := Reduction.MachineTransfer.transferAtInTime Tape.accumulator Tape.output
324
+ (by decide) id false .reverseOutput none (program headerPlan plan) rfl
325
+ loop.finalTapes (loop.finalAmbient, ()) none
326
+ simpa only [acc, out, List.reverse_reverse, List.length_reverse, List.map_id,
327
+ List.append_nil, finalTapes, machine, FinTM2.step] using! run
328
+ let first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ headerRun loop.execution
329
+ let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first finish
330
+ exact {
331
+ finalAmbient := loop.finalAmbient
332
+ finalTapes := finalTapes
333
+ execution := {
334
+ toEvalsTo := run.toEvalsTo
335
+ steps_le_m := by
336
+ have hb := run.steps_le_m
337
+ unfold rawBudget
338
+ omega }
339
+ output := by simp [finalTapes, Reduction.MachineTransfer.tapesAt] }
340
+
341
+ end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
342
+
343
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFTemplate
344
+
345
+ open Target PCP
346
+
347
+ inductive Reference where
348
+ | query : Fin 12 → Reference
349
+ | auxiliary : Fin 9 → Reference
350
+ deriving DecidableEq
351
+
352
+ structure LiteralTemplate where
353
+ reference : Reference
354
+ positive : Bool
355
+ deriving DecidableEq
356
+
357
+ abbrev ClauseTemplate := Vector LiteralTemplate 3
358
+
359
+ def queryLiteral (bits : Fin 12 → Bool) (i : Fin 12) : LiteralTemplate :=
360
+ ⟨.query i, !(bits i)⟩
361
+
362
+ def auxiliaryLiteral (j : Fin 9) (positive : Bool) : LiteralTemplate :=
363
+ ⟨.auxiliary j, positive⟩
364
+
365
+ def tautologyTemplate : ClauseTemplate :=
366
+ #v[⟨.query 0, true⟩, ⟨.query 0, false⟩, ⟨.query 0, true⟩]
367
+
368
+ def chainTemplates (bits : Fin 12 → Bool) : Vector ClauseTemplate 10 :=
369
+ #v[
370
+ #v[queryLiteral bits 0, queryLiteral bits 1, auxiliaryLiteral 0 true],
371
+ #v[auxiliaryLiteral 0 false, queryLiteral bits 2, auxiliaryLiteral 1 true],
372
+ #v[auxiliaryLiteral 1 false, queryLiteral bits 3, auxiliaryLiteral 2 true],
373
+ #v[auxiliaryLiteral 2 false, queryLiteral bits 4, auxiliaryLiteral 3 true],
374
+ #v[auxiliaryLiteral 3 false, queryLiteral bits 5, auxiliaryLiteral 4 true],
375
+ #v[auxiliaryLiteral 4 false, queryLiteral bits 6, auxiliaryLiteral 5 true],
376
+ #v[auxiliaryLiteral 5 false, queryLiteral bits 7, auxiliaryLiteral 6 true],
377
+ #v[auxiliaryLiteral 6 false, queryLiteral bits 8, auxiliaryLiteral 7 true],
378
+ #v[auxiliaryLiteral 7 false, queryLiteral bits 9, auxiliaryLiteral 8 true],
379
+ #v[auxiliaryLiteral 8 false, queryLiteral bits 10, queryLiteral bits 11]]
380
+
381
+ def blockTemplates (accepted : Bool) (bits : Fin 12 → Bool) : Vector ClauseTemplate 10 :=
382
+ if accepted then Vector.replicate 10 tautologyTemplate else chainTemplates bits
383
+
384
+ def templates (accepted : Bool) (bits : Fin 12 → Bool) : List ClauseTemplate :=
385
+ (blockTemplates accepted bits).toList
386
+
387
+ def literalAt (accepted : Bool) (bits : Fin 12 → Bool)
388
+ (clause : Fin 10) (slot : Fin 3) : LiteralTemplate :=
389
+ (blockTemplates accepted bits)[clause][slot]
390
+
391
+ @[simp] theorem templates_length (accepted : Bool) (bits : Fin 12 → Bool) :
392
+ (templates accepted bits).length = 10 := Vector.length_toList
393
+
394
+ theorem templates_true (bits : Fin 12 → Bool) :
395
+ templates true bits = List.replicate 10 tautologyTemplate := by rfl
396
+
397
+ theorem templates_false (bits : Fin 12 → Bool) :
398
+ templates false bits = (chainTemplates bits).toList := by rfl
399
+
400
+ def literalTemplates (accepted : Bool) (bits : Fin 12 → Bool) : List LiteralTemplate :=
401
+ (templates accepted bits).flatMap fun c => [(c)[0], (c)[1], (c)[2]]
402
+
403
+ theorem literalTemplates_length (accepted : Bool) (bits : Fin 12 → Bool) :
404
+ (literalTemplates accepted bits).length = 30 := by
405
+ unfold literalTemplates
406
+ rw [VerifierToCNF.length_flatMap_constant _ _ 3 (by intro c hc; rfl), templates_length]
407
+
408
+ def literalWords (index : Reference → Nat) (literal : LiteralTemplate) : List Nat :=
409
+ [index literal.reference, if literal.positive then 1 else 0]
410
+
411
+ def clauseWords (index : Reference → Nat) (clause : ClauseTemplate) : List Nat :=
412
+ literalWords index clause[0] ++ literalWords index clause[1] ++ literalWords index clause[2]
413
+
414
+ def words (accepted : Bool) (bits : Fin 12 → Bool) (index : Reference → Nat) : List Nat :=
415
+ (templates accepted bits).flatMap (clauseWords index)
416
+
417
+ theorem words_length (accepted : Bool) (bits : Fin 12 → Bool) (index : Reference → Nat) :
418
+ (words accepted bits index).length = 60 := by
419
+ unfold words
420
+ rw [VerifierToCNF.length_flatMap_constant _ _ 6
421
+ (by intro c hc; simp [clauseWords, literalWords]), templates_length]
422
+
423
+ variable (V : VerifierToCNF.FiniteVerifier 12) (e : Fin V.events)
424
+ (p : VerifierToCNF.PatternIndex 12)
425
+
426
+ def resolve : Reference → Fin (VerifierToCNF.outputVariables V)
427
+ | .query i => VerifierToCNF.oldIndex V (V.query e i)
428
+ | .auxiliary j => VerifierToCNF.freshIndex V e p j
429
+
430
+ theorem resolve_query_value (i : Fin 12) :
431
+ (resolve V e p (.query i)).val = (V.query e i).val := by
432
+ simp only [resolve, VerifierToCNF.oldIndex, Fin.val_castAdd]
433
+
434
+ theorem resolve_auxiliary_value (j : Fin 9) :
435
+ (resolve V e p (.auxiliary j)).val =
436
+ V.«variables» + ((e.val * 4096 + p.val) * 9 + j.val) := by
437
+ change (VerifierToCNF.freshIndex V e p j).val = _
438
+ exact (VerifierToCNF.freshIndex_value V e p j).trans
439
+ (congrArg (fun k : Nat => V.«variables» + ((e.val * k + p.val) * 9 + j.val))
440
+ (show (VerifierToCNF.patterns 12).length = 4096 from VerifierToCNF.patterns_length 12))
441
+
442
+ def instantiateLiteral (literal : LiteralTemplate) : Literal (VerifierToCNF.outputVariables V) :=
443
+ ⟨resolve V e p literal.reference, literal.positive⟩
444
+
445
+ def instantiateClause (clause : ClauseTemplate) : Clause (VerifierToCNF.outputVariables V) :=
446
+ #v[instantiateLiteral V e p clause[0], instantiateLiteral V e p clause[1],
447
+ instantiateLiteral V e p clause[2]]
448
+
449
+ theorem splitLong_twelve {n : Nat} (ls : Fin 12 → Literal n) (ys : Fin 9 → Fin n) :
450
+ VerifierToCNF.splitLong (List.ofFn ls) (List.ofFn ys) =
451
+ [#v[ls 0, ls 1, ⟨ys 0, true⟩],
452
+ #v[⟨ys 0, false⟩, ls 2, ⟨ys 1, true⟩],
453
+ #v[⟨ys 1, false⟩, ls 3, ⟨ys 2, true⟩],
454
+ #v[⟨ys 2, false⟩, ls 4, ⟨ys 3, true⟩],
455
+ #v[⟨ys 3, false⟩, ls 5, ⟨ys 4, true⟩],
456
+ #v[⟨ys 4, false⟩, ls 6, ⟨ys 5, true⟩],
457
+ #v[⟨ys 5, false⟩, ls 7, ⟨ys 6, true⟩],
458
+ #v[⟨ys 6, false⟩, ls 8, ⟨ys 7, true⟩],
459
+ #v[⟨ys 7, false⟩, ls 9, ⟨ys 8, true⟩],
460
+ #v[⟨ys 8, false⟩, ls 10, ls 11]] := by
461
+ simp only [List.ofFn_succ, List.ofFn_zero, VerifierToCNF.splitLong]
462
+ rfl
463
+
464
+ theorem instantiate_templates :
465
+ (templates (V.accepts e (VerifierToCNF.patternAt 12 p))
466
+ (VerifierToCNF.patternAt 12 p)).map (instantiateClause V e p) =
467
+ VerifierToCNF.block V (by decide) e p := by
468
+ cases h : V.accepts e (VerifierToCNF.patternAt 12 p) with
469
+ | false =>
470
+ simp only [h, templates_false, VerifierToCNF.block, Bool.false_eq_true, ↓reduceIte,
471
+ VerifierToCNF.forbiddenClause, VerifierToCNF.auxiliaryNames]
472
+ rw [splitLong_twelve]
473
+ rfl
474
+ | true =>
475
+ simp only [h, templates_true, VerifierToCNF.block, ↓reduceIte, List.map_replicate]
476
+ rfl
477
+
478
+ theorem instantiate_templates_of_acceptance (accepted : Bool)
479
+ (h : V.accepts e (VerifierToCNF.patternAt 12 p) = accepted) :
480
+ (templates accepted (VerifierToCNF.patternAt 12 p)).map (instantiateClause V e p) =
481
+ VerifierToCNF.block V (by decide) e p := by
482
+ rw [← h]
483
+ exact instantiate_templates V e p
484
+
485
+ theorem instantiateClause_words (clause : ClauseTemplate) :
486
+ Complexity.clauseWords (instantiateClause V e p clause) =
487
+ clauseWords (fun r => (resolve V e p r).val) clause := rfl
488
+
489
+ theorem words_eq_block :
490
+ words (V.accepts e (VerifierToCNF.patternAt 12 p)) (VerifierToCNF.patternAt 12 p)
491
+ (fun r => (resolve V e p r).val) =
492
+ (VerifierToCNF.block V (by decide) e p).flatMap Complexity.clauseWords := by
493
+ rw [← instantiate_templates V e p]
494
+ simp only [List.flatMap_map, instantiateClause_words]
495
+ rfl
496
+
497
+ theorem block_words_length :
498
+ ((VerifierToCNF.block V (by decide) e p).flatMap Complexity.clauseWords).length = 60 := by
499
+ rw [← words_eq_block V e p]
500
+ exact words_length _ _ _
501
+
502
+ end MinUncutGames.Foundations.Complexity.FinalCNFTemplate
503
+
504
+ namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
505
+
506
+ open PCP PCP.AlphabetTable FinalCNFTemplate
507
+
508
+ def referenceValue (vertices tail head row pattern : Nat) : Reference → Nat
509
+ | .query i => if i.val < 6 then 6 * tail + i.val else 6 * head + (i.val - 6)
510
+ | .auxiliary j => 6 * vertices + 36864 * row + (9 * pattern + j.val)
511
+
512
+ def auxiliaryFlag : Reference → Bool
513
+ | .query _ => false
514
+ | .auxiliary _ => true
515
+
516
+ def tailFlag : Reference → Bool
517
+ | .query i => decide (i.val < 6)
518
+ | .auxiliary _ => false
519
+
520
+ def headFlag : Reference → Bool
521
+ | .query i => decide (6 ≤ i.val)
522
+ | .auxiliary _ => false
523
+
524
+ theorem pattern_lt (p : VerifierToCNF.PatternIndex 12) : p.val < 4096 := by
525
+ have hlen : (VerifierToCNF.patterns 12).length = 4096 := VerifierToCNF.patterns_length 12
526
+ exact lt_of_lt_of_eq p.isLt hlen
527
+
528
+ def referenceOffset (p : VerifierToCNF.PatternIndex 12) : Reference → Fin 36864
529
+ | .query i => ⟨if i.val < 6 then i.val else i.val - 6, by split <;> omega⟩
530
+ | .auxiliary j => ⟨9 * p.val + j.val, by have hp := pattern_lt p; omega⟩
531
+
532
+ def literalPlan (p : VerifierToCNF.PatternIndex 12) (literal : Ambient → LiteralTemplate) : Plan :=
533
+ [.scaledIf 0 6 (fun state => auxiliaryFlag (literal state).reference),
534
+ .scaledIf 2 6 (fun state => tailFlag (literal state).reference),
535
+ .scaledIf 3 6 (fun state => headFlag (literal state).reference),
536
+ .scaledIf 4 36864 (fun state => auxiliaryFlag (literal state).reference),
537
+ .bounded (fun state => referenceOffset p (literal state).reference),
538
+ .literal [false],
539
+ .bit (fun state => (literal state).positive)]
540
+
541
+ theorem literalPlan_length (p : VerifierToCNF.PatternIndex 12)
542
+ (literal : Ambient → LiteralTemplate) : (literalPlan p literal).length = 7 := rfl
543
+
544
+ theorem literalPlan_bits (p : VerifierToCNF.PatternIndex 12)
545
+ (literal : Ambient → LiteralTemplate) (vertices darts tail head row : Nat)
546
+ (ambient : Ambient) :
547
+ (literalPlan p literal).flatMap
548
+ (Emitter.commandBits (values vertices darts tail head row) ambient) =
549
+ encodeWords (FinalCNFTemplate.literalWords
550
+ (referenceValue vertices tail head row p.val) (literal ambient)) := by
551
+ rcases h : literal ambient with ⟨reference, positive⟩
552
+ cases reference with
553
+ | query i =>
554
+ by_cases hi : i.val < 6
555
+ · simp [literalPlan, Emitter.commandBits, h, auxiliaryFlag, tailFlag, headFlag,
556
+ referenceOffset, referenceValue, FinalCNFTemplate.literalWords, values,
557
+ hi, show ¬ 6 ≤ i.val by omega, encodeWords, encodeWord, List.replicate_add,
558
+ List.append_assoc, -List.replicate_append_replicate]
559
+ rfl
560
+ · simp [literalPlan, Emitter.commandBits, h, auxiliaryFlag, tailFlag, headFlag,
561
+ referenceOffset, referenceValue, FinalCNFTemplate.literalWords, values,
562
+ hi, show 6 ≤ i.val by omega, encodeWords, encodeWord, List.replicate_add,
563
+ List.append_assoc, -List.replicate_append_replicate]
564
+ rfl
565
+ | auxiliary j =>
566
+ simp [literalPlan, Emitter.commandBits, h, auxiliaryFlag, tailFlag, headFlag,
567
+ referenceOffset, referenceValue, FinalCNFTemplate.literalWords, values,
568
+ encodeWords, encodeWord, List.replicate_add, List.append_assoc,
569
+ -List.replicate_append_replicate]
570
+ rfl
571
+
572
+ def patternLiteral (p : VerifierToCNF.PatternIndex 12) (clause : Fin 10) (slot : Fin 3)
573
+ (ambient : Ambient) : LiteralTemplate :=
574
+ literalAt (ambient.2 (FinalCNFPattern.patternRelationIndex p))
575
+ (VerifierToCNF.patternAt 12 p) clause slot
576
+
577
+ def patternPlan (p : VerifierToCNF.PatternIndex 12) : Plan :=
578
+ (List.finRange 10).flatMap fun clause =>
579
+ (List.finRange 3).flatMap fun slot => literalPlan p (patternLiteral p clause slot)
580
+
581
+ def rowPlan : Plan :=
582
+ (List.finRange (VerifierToCNF.patterns 12).length).flatMap patternPlan
583
+
584
+ theorem patternPlan_length (p : VerifierToCNF.PatternIndex 12) :
585
+ (patternPlan p).length = 210 := by
586
+ unfold patternPlan
587
+ rw [VerifierToCNF.length_flatMap_constant _ _ 21]
588
+ · simp
589
+ · intro clause hclause
590
+ rw [VerifierToCNF.length_flatMap_constant _ _ 7]
591
+ · simp
592
+ · intro slot hslot
593
+ exact literalPlan_length _ _
594
+
595
+ theorem rowPlan_length : rowPlan.length = 860160 := by
596
+ unfold rowPlan
597
+ rw [VerifierToCNF.length_flatMap_constant _ _ 210]
598
+ · calc
599
+ _ = 2 ^ 12 * 210 := by rw [List.length_finRange, VerifierToCNF.patterns_length]
600
+ _ = 860160 := by decide
601
+ · intro p hp
602
+ exact patternPlan_length p
603
+
604
+ theorem encodeWords_flatMap {α : Type*} (xs : List α) (words : α → List Nat) :
605
+ encodeWords (xs.flatMap words) = xs.flatMap (fun x => encodeWords (words x)) := by
606
+ induction xs with
607
+ | nil => rfl
608
+ | cons x xs ih => simp only [List.flatMap_cons, encodeWords_append, ih]
609
+
610
+ theorem patternPlan_bits (p : VerifierToCNF.PatternIndex 12)
611
+ (vertices darts tail head row : Nat) (ambient : Ambient) :
612
+ (patternPlan p).flatMap
613
+ (Emitter.commandBits (values vertices darts tail head row) ambient) =
614
+ encodeWords (FinalCNFTemplate.words
615
+ (ambient.2 (FinalCNFPattern.patternRelationIndex p))
616
+ (VerifierToCNF.patternAt 12 p) (referenceValue vertices tail head row p.val)) := by
617
+ unfold patternPlan
618
+ simp only [List.flatMap_assoc]
619
+ simp_rw [literalPlan_bits]
620
+ have hclauses :
621
+ (List.finRange 10).map
622
+ (fun c => (blockTemplates (ambient.2 (FinalCNFPattern.patternRelationIndex p))
623
+ (VerifierToCNF.patternAt 12 p))[c]) =
624
+ templates (ambient.2 (FinalCNFPattern.patternRelationIndex p))
625
+ (VerifierToCNF.patternAt 12 p) := by
626
+ rw [← List.ofFn_eq_map]
627
+ change List.ofFn (fun c : Fin 10 =>
628
+ (blockTemplates (ambient.2 (FinalCNFPattern.patternRelationIndex p))
629
+ (VerifierToCNF.patternAt 12 p))[c.val]) = _
630
+ rw [← Vector.toList_ofFn, Vector.ofFn_getElem]
631
+ rfl
632
+ unfold FinalCNFTemplate.words
633
+ rw [← hclauses, List.flatMap_map, encodeWords_flatMap]
634
+ apply List.flatMap_congr
635
+ intro clause hclause
636
+ simp only [List.finRange, List.ofFn_succ, List.ofFn_zero, List.flatMap_cons,
637
+ List.flatMap_nil, patternLiteral, literalAt, FinalCNFTemplate.clauseWords,
638
+ encodeWords_append, List.append_nil, List.append_assoc]
639
+ rfl
640
+
641
+ theorem referenceValue_eq_resolve (table : GraphTables.Table) (e : Fin table.darts)
642
+ (p : VerifierToCNF.PatternIndex 12) (reference : Reference) :
643
+ referenceValue table.vertices table.rows[e].tail.val
644
+ table.rows[table.rows[e].reverseIndex].tail.val e.val p.val reference =
645
+ (resolve (FinalCNFPattern.tableVerifier table) e p reference).val := by
646
+ cases reference with
647
+ | query i =>
648
+ rw [resolve_query_value]
649
+ refine Fin.addCases (m := 6) (n := 6) (fun j => ?_) (fun j => ?_) i
650
+ · rw [FinalBooleanVerifier.query_tail]
651
+ simp only [referenceValue, Fin.val_castAdd, j.isLt, ite_true]
652
+ change 6 * table.rows[e].tail.val + j.val = j.val + 6 * table.rows[e].tail.val
653
+ omega
654
+ · rw [FinalBooleanVerifier.query_head]
655
+ simp only [referenceValue, Fin.val_natAdd]
656
+ split
657
+ · omega
658
+ · change 6 * table.rows[table.rows[e].reverseIndex].tail.val +
659
+ (6 + j.val - 6) = j.val + 6 * table.rows[table.rows[e].reverseIndex].tail.val
660
+ omega
661
+ | auxiliary j =>
662
+ rw [resolve_auxiliary_value]
663
+ change 6 * table.vertices + 36864 * e.val + (9 * p.val + j.val) =
664
+ table.vertices * 6 + ((e.val * 4096 + p.val) * 9 + j.val)
665
+ omega
666
+
667
+ theorem rowPlan_bits (table : GraphTables.Table) (e : Fin table.darts) :
668
+ rowPlan.flatMap (Emitter.commandBits
669
+ (values table.vertices table.darts table.rows[e].tail.val
670
+ table.rows[table.rows[e].reverseIndex].tail.val e.val)
671
+ ((), fun i => table.rows[e].relation[i])) =
672
+ encodeWords ((VerifierToCNF.eventBlock (FinalCNFPattern.tableVerifier table)
673
+ (by decide) e).flatMap Complexity.clauseWords) := by
674
+ unfold rowPlan VerifierToCNF.eventBlock
675
+ simp only [List.flatMap_assoc]
676
+ rw [encodeWords_flatMap]
677
+ apply List.flatMap_congr
678
+ intro p hp
679
+ rw [patternPlan_bits]
680
+ dsimp only
681
+ rw [FinalCNFPattern.pattern_lookup_eq_verifier_accepts]
682
+ have href := funext (referenceValue_eq_resolve table e p)
683
+ rw [href]
684
+ exact congrArg encodeWords (words_eq_block (FinalCNFPattern.tableVerifier table) e p)
685
+
686
+ end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
687
+
688
+ end OAI
lean/OAI/Computability/MinUncut/Games/FiniteNoise.lean ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Encoding.ThreeBitTest
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ namespace MinUncutGames.Reduction.FiniteNoise
8
+
9
+ open scoped BigOperators
10
+ open MinUncutGames.Foundations.Hastad (noiseWeight)
11
+
12
+ def realizedBit {D : Nat} (z : Fin D) : Bool := decide (z.val = 0)
13
+
14
+ def realizedNoise {A : Type*} {D : Nat} (z : A → Fin D) : A → Bool :=
15
+ fun a => realizedBit (z a)
16
+
17
+ theorem realizedBit_eq_true_iff {D : Nat} (positive : 0 < D) (z : Fin D) :
18
+ realizedBit z = true ↔ z = ⟨0, positive⟩ := by
19
+ simp [realizedBit, Fin.ext_iff]
20
+
21
+ theorem coordinate_fiber_sum {D : Nat} (positive : 0 < D) (b : Bool) :
22
+ (∑ z : Fin D, if realizedBit z = b then (D : ℝ)⁻¹ else 0) =
23
+ if b then (D : ℝ)⁻¹ else 1 - (D : ℝ)⁻¹ := by
24
+ have hd : (D : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt positive
25
+ have ht : (∑ z : Fin D, if realizedBit z = true then (D : ℝ)⁻¹ else 0) =
26
+ (D : ℝ)⁻¹ := by
27
+ simp_rw [realizedBit_eq_true_iff positive]
28
+ simp
29
+ have htotal :
30
+ (∑ z : Fin D, if realizedBit z = false then (D : ℝ)⁻¹ else 0) +
31
+ (∑ z : Fin D, if realizedBit z = true then (D : ℝ)⁻¹ else 0) = 1 := by
32
+ rw [← Finset.sum_add_distrib]
33
+ have he (z : Fin D) :
34
+ (if realizedBit z = false then (D : ℝ)⁻¹ else 0) +
35
+ (if realizedBit z = true then (D : ℝ)⁻¹ else 0) = (D : ℝ)⁻¹ := by
36
+ cases realizedBit z <;> simp
37
+ simp_rw [he]
38
+ simp [hd]
39
+ cases b <;> simp only [Bool.false_eq_true, ite_false, ite_true]
40
+ · linarith
41
+ · exact ht
42
+
43
+ variable {A : Type*} [Fintype A] [DecidableEq A]
44
+
45
+ theorem noiseWeight_eq_fiber_sum {D : Nat} (positive : 0 < D) (μ : A → Bool) :
46
+ noiseWeight ((D : ℝ)⁻¹) μ =
47
+ ∑ z : A → Fin D,
48
+ ∏ a, if realizedBit (z a) = μ a then (D : ℝ)⁻¹ else 0 := by
49
+ rw [← Fintype.prod_sum (fun (a : A) (z : Fin D) =>
50
+ if realizedBit z = μ a then (D : ℝ)⁻¹ else 0)]
51
+ unfold noiseWeight
52
+ apply Finset.prod_congr rfl
53
+ intro a _
54
+ exact (coordinate_fiber_sum positive (μ a)).symm
55
+
56
+ omit [DecidableEq A] in
57
+ theorem fiber_product_eq_indicator {D : Nat} (z : A → Fin D) (μ : A → Bool) :
58
+ (∏ a, if realizedBit (z a) = μ a then (D : ℝ)⁻¹ else 0) =
59
+ if realizedNoise z = μ then ((D : ℝ)⁻¹) ^ Fintype.card A else 0 := by
60
+ classical
61
+ by_cases h : realizedNoise z = μ
62
+ · rw [ite_eq_left h]
63
+ have ha (a : A) : realizedBit (z a) = μ a := congrFun h a
64
+ simp [ha]
65
+ · rw [ite_eq_right h]
66
+ obtain ⟨a, ha⟩ := Function.ne_iff.mp h
67
+ apply Finset.prod_eq_zero (Finset.mem_univ a)
68
+ exact ite_eq_right ha
69
+
70
+ theorem expect_realizedNoise {D : Nat} (positive : 0 < D) (H : (A → Bool) → ℝ) :
71
+ (𝔼 z : A → Fin D, H (realizedNoise z)) =
72
+ ∑ μ : A → Bool, noiseWeight ((D : ℝ)⁻¹) μ * H μ := by
73
+ classical
74
+ symm
75
+ simp_rw [noiseWeight_eq_fiber_sum positive, Finset.sum_mul]
76
+ rw [Finset.sum_comm]
77
+ simp_rw [fiber_product_eq_indicator]
78
+ have he (z : A → Fin D) :
79
+ (∑ μ : A → Bool,
80
+ (if realizedNoise z = μ then ((D : ℝ)⁻¹) ^ Fintype.card A else 0) * H μ) =
81
+ ((D : ℝ)⁻¹) ^ Fintype.card A * H (realizedNoise z) := by
82
+ simp [eq_comm]
83
+ simp_rw [he]
84
+ rw [Fintype.expect_eq_sum_div_card]
85
+ simp only [Fintype.card_fun, Fintype.card_fin, Nat.cast_pow]
86
+ rw [div_eq_mul_inv, inv_pow]
87
+ rw [← Finset.mul_sum]
88
+ exact mul_comm _ _
89
+
90
+ end MinUncutGames.Reduction.FiniteNoise
91
+
92
+ end
93
+
94
+ end OAI
lean/OAI/Computability/MinUncut/Games/GraphCounterModel.lean ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Machines.MachineLazyTableRuntime
3
+
4
+ namespace OAI
5
+
6
+ namespace MinUncutGames.Foundations.Complexity.GraphCounterModel
7
+
8
+ open Turing
9
+
10
+ inductive ExtraTape where
11
+ | input | archive | scratch | output
12
+ deriving DecidableEq
13
+
14
+ protected abbrev ExtraTape.enumList : List ExtraTape := [.input, .archive, .scratch, .output]
15
+
16
+ protected theorem ExtraTape.enumList_getElem?_ctorIdx_eq (x : ExtraTape) :
17
+ ExtraTape.enumList[x.ctorIdx]? = some x := by
18
+ cases x <;> rfl
19
+
20
+ protected theorem ExtraTape.enumList_nodup : ExtraTape.enumList.Nodup := by decide
21
+
22
+ instance : Fintype ExtraTape where
23
+ elems := ⟨ExtraTape.enumList, ExtraTape.enumList_nodup⟩
24
+ complete x := by cases x <;> decide
25
+
26
+ inductive ExtraLabel where
27
+ | copyFirst | copySecond | seed | headerFirst | headerSecond
28
+ | clearInput | clockCopy | archiveCopy | finalReverse
29
+ deriving DecidableEq
30
+
31
+ protected abbrev ExtraLabel.enumList : List ExtraLabel := [.copyFirst, .copySecond, .seed,
32
+ .headerFirst, .headerSecond, .clearInput, .clockCopy, .archiveCopy, .finalReverse]
33
+
34
+ protected theorem ExtraLabel.enumList_getElem?_ctorIdx_eq (x : ExtraLabel) :
35
+ ExtraLabel.enumList[x.ctorIdx]? = some x := by
36
+ cases x <;> rfl
37
+
38
+ protected theorem ExtraLabel.enumList_nodup : ExtraLabel.enumList.Nodup := by decide
39
+
40
+ instance : Fintype ExtraLabel where
41
+ elems := ⟨ExtraLabel.enumList, ExtraLabel.enumList_nodup⟩
42
+ complete x := by cases x <;> decide
43
+
44
+ abbrev Tape := Fin 3 ⊕ ExtraTape
45
+ abbrev Label := Fin 5 ⊕ ExtraLabel
46
+ abbrev Alphabet (_ : Tape) := Bool
47
+ abbrev State := MachineLogCounter.State × Option Bool
48
+
49
+ def initialState : State := (MachineLogCounter.initialState, none)
50
+
51
+ def clockLabel : Option (Fin 5) → Option Label
52
+ | none => some (.inr .clearInput)
53
+ | some l => some (.inl l)
54
+
55
+ def clockStatement : TM2.Stmt MachineLogCounter.Alphabet (Fin 5) MachineLogCounter.State →
56
+ TM2.Stmt Alphabet Label State
57
+ | .push k f next => .push (.inl k) (fun state => f state.1) (clockStatement next)
58
+ | .peek k f next => .peek (.inl k) (fun state x => (f state.1 x, state.2)) (clockStatement next)
59
+ | .pop k f next => .pop (.inl k) (fun state x => (f state.1 x, state.2)) (clockStatement next)
60
+ | .load f next => .load (fun state => (f state.1, state.2)) (clockStatement next)
61
+ | .branch f yes no => .branch (fun state => f state.1) (clockStatement yes) (clockStatement no)
62
+ | .goto f => .goto (fun state => .inl (f state.1))
63
+ | .halt => .goto (fun _ => .inr .clearInput)
64
+
65
+ def readHeader (again next : Label) : TM2.Stmt Alphabet Label State :=
66
+ .pop (.inr .input) (fun state head => (state.1, head))
67
+ (.branch (fun state => state.2.getD false)
68
+ (.push (.inl 0) (fun _ => true) (.goto fun _ => again))
69
+ (.load (fun state => (state.1, none)) (.goto fun _ => next)))
70
+
71
+ def program : Label → TM2.Stmt Alphabet Label State
72
+ | .inl l => clockStatement (MachineLogCounter.program l)
73
+ | .inr .copyFirst => Reduction.MachineTransfer.loopAt (.inr .input) (.inr .scratch)
74
+ id false (.inr .copyFirst) (some (.inr .copySecond))
75
+ | .inr .copySecond => MachineCopy.forkLoop (.inr .scratch) (.inr .input) (.inr .archive)
76
+ false (.inr .copySecond) (some (.inr .seed))
77
+ | .inr .seed => .push (.inl 0) (fun _ => false) (.goto fun _ => .inr .headerFirst)
78
+ | .inr .headerFirst => readHeader (.inr .headerFirst) (.inr .headerSecond)
79
+ | .inr .headerSecond => readHeader (.inr .headerSecond) (.inl 0)
80
+ | .inr .clearInput => MachineDrain.drain (.inr .input) (.inr .clearInput)
81
+ (some (.inr .clockCopy))
82
+ | .inr .clockCopy => Reduction.MachineTransfer.loopAt (.inl 2) (.inr .scratch)
83
+ id false (.inr .clockCopy) (some (.inr .archiveCopy))
84
+ | .inr .archiveCopy => Reduction.MachineTransfer.loopAt (.inr .archive) (.inr .scratch)
85
+ id false (.inr .archiveCopy) (some (.inr .finalReverse))
86
+ | .inr .finalReverse => Reduction.MachineTransfer.loopAt (.inr .scratch) (.inr .output)
87
+ id false (.inr .finalReverse) none
88
+
89
+ def machine : FinTM2 where
90
+ K := Tape
91
+ k₀ := .inr .input
92
+ k₁ := .inr .output
93
+ Γ := Alphabet
94
+ Λ := Label
95
+ main := .inr .copyFirst
96
+ σ := State
97
+ initialState := initialState
98
+ m := program
99
+
100
+ def clockTapes (tapes : Fin 3 → List Bool) (extra : ExtraTape → List Bool) : Tape → List Bool
101
+ | .inl k => tapes k
102
+ | .inr k => extra k
103
+
104
+ def clockConfiguration (extra : ExtraTape → List Bool) (register : Option Bool)
105
+ (c : TM2.Cfg MachineLogCounter.Alphabet (Fin 5) MachineLogCounter.State) :
106
+ TM2.Cfg Alphabet Label State := ⟨clockLabel c.l, (c.var, register), clockTapes c.stk extra⟩
107
+
108
+ theorem clockTapes_update (tapes : Fin 3 → List Bool) (extra : ExtraTape → List Bool)
109
+ (k : Fin 3) (word : List Bool) :
110
+ clockTapes (Function.update tapes k word) extra =
111
+ Function.update (clockTapes tapes extra) (.inl k) word := by
112
+ funext tape
113
+ cases tape <;> simp [clockTapes, Function.comp_def]
114
+
115
+ theorem clockStatement_simulation (extra : ExtraTape → List Bool) (register : Option Bool)
116
+ (statement : TM2.Stmt MachineLogCounter.Alphabet (Fin 5) MachineLogCounter.State)
117
+ (state : MachineLogCounter.State) (tapes : Fin 3 → List Bool) :
118
+ TM2.stepAux (clockStatement statement) (state, register) (clockTapes tapes extra) =
119
+ clockConfiguration extra register (TM2.stepAux statement state tapes) := by
120
+ induction statement generalizing state tapes with
121
+ | push k f next ih =>
122
+ simp only [clockStatement, TM2.stepAux, clockTapes]
123
+ rw [← clockTapes_update]
124
+ exact ih state (Function.update tapes k (f state :: tapes k))
125
+ | peek k f next ih =>
126
+ simpa only [clockStatement, TM2.stepAux, clockTapes] using ih (f state (tapes k).head?) tapes
127
+ | pop k f next ih =>
128
+ simp only [clockStatement, TM2.stepAux, clockTapes]
129
+ rw [← clockTapes_update]
130
+ exact ih (f state (tapes k).head?) (Function.update tapes k (tapes k).tail)
131
+ | load f next ih =>
132
+ simpa only [clockStatement, TM2.stepAux] using ih (f state) tapes
133
+ | branch f yes no ihYes ihNo =>
134
+ cases h : f state with
135
+ | false => simpa only [clockStatement, TM2.stepAux, h, Bool.cond_false] using ihNo state tapes
136
+ | true => simpa only [clockStatement, TM2.stepAux, h, Bool.cond_true] using ihYes state tapes
137
+ | goto f => rfl
138
+ | halt => rfl
139
+
140
+ theorem clockStep (extra : ExtraTape → List Bool) (register : Option Bool)
141
+ (a b : MachineLogCounter.machine.Cfg)
142
+ (h : MachineLogCounter.machine.step a = some b) :
143
+ TM2.step program (clockConfiguration extra register a) =
144
+ some (clockConfiguration extra register b) := by
145
+ cases a with
146
+ | mk label state tapes =>
147
+ cases label with
148
+ | none => cases h
149
+ | some label =>
150
+ have hb := Option.some.inj h
151
+ subst b
152
+ exact congrArg some (clockStatement_simulation extra register
153
+ (MachineLogCounter.program label) state tapes)
154
+
155
+ def clockInTime (extra : ExtraTape → List Bool) (register : Option Bool) (n : Nat) :
156
+ StateTransition.EvalsToInTime (TM2.step program)
157
+ (clockConfiguration extra register (initList MachineLogCounter.machine (encodeWord n)))
158
+ (some (clockConfiguration extra register
159
+ (haltList MachineLogCounter.machine (encodeWord (n.log2 + 1))))) (8 * n + 4) :=
160
+ MachineComposition.liftExecutionInTime _ _ (clockConfiguration extra register)
161
+ (clockStep extra register) (MachineLogCounter.outputsInTime n)
162
+
163
+ open Turing
164
+
165
+ def startExtra (input archive : List Bool) : ExtraTape → List Bool
166
+ | .input => input
167
+ | .archive => archive
168
+ | _ => []
169
+
170
+ def startMemory (input archive sum : List Bool) : Tape → List Bool
171
+ | .inl k => if k = 0 then sum else []
172
+ | .inr k => startExtra input archive k
173
+
174
+ theorem startMemory_input_update (input archive sum replacement : List Bool) :
175
+ Function.update (startMemory input archive sum) (.inr .input) replacement =
176
+ startMemory replacement archive sum := by
177
+ funext tape
178
+ cases tape with
179
+ | inl k => simp [startMemory]
180
+ | inr k => cases k <;> simp [startMemory, startExtra]
181
+
182
+ theorem startMemory_sum_update (input archive sum replacement : List Bool) :
183
+ Function.update (startMemory input archive sum) (.inl 0) replacement =
184
+ startMemory input archive replacement := by
185
+ funext tape
186
+ cases tape with
187
+ | inl k => by_cases h : k = 0 <;> simp [startMemory, h]
188
+ | inr k => simp [startMemory]
189
+
190
+ theorem headerStep_zero (again next : Label)
191
+ (atHeader : program again = readHeader again next)
192
+ (suffix archive : List Bool) (sum : Nat)
193
+ (state : MachineLogCounter.State) (register : Option Bool) :
194
+ TM2.step program
195
+ ⟨some again, (state, register), startMemory (encodeWord 0 ++ suffix) archive (encodeWord sum)⟩ =
196
+ some ⟨some next, (state, none), startMemory suffix archive (encodeWord sum)⟩ := by
197
+ change some (TM2.stepAux (program again) _ _) = _
198
+ rw [atHeader]
199
+ simp only [readHeader, TM2.stepAux, startMemory, startExtra, encodeWord,
200
+ List.replicate_zero, List.nil_append, List.singleton_append, List.head?_cons,
201
+ List.tail_cons, Option.getD_some, Bool.cond_false]
202
+ rw [startMemory_input_update]
203
+
204
+ theorem headerStep_succ (again next : Label)
205
+ (atHeader : program again = readHeader again next)
206
+ (n sum : Nat) (suffix archive : List Bool)
207
+ (state : MachineLogCounter.State) (register : Option Bool) :
208
+ TM2.step program
209
+ ⟨some again, (state, register),
210
+ startMemory (encodeWord (n + 1) ++ suffix) archive (encodeWord sum)⟩ =
211
+ some ⟨some again, (state, some true),
212
+ startMemory (encodeWord n ++ suffix) archive (encodeWord (sum + 1))⟩ := by
213
+ change some (TM2.stepAux (program again) _ _) = _
214
+ rw [atHeader]
215
+ simp only [readHeader, TM2.stepAux, startMemory, startExtra, encodeWord,
216
+ List.replicate_succ, List.cons_append, List.head?_cons, List.tail_cons,
217
+ Option.getD_some, Bool.cond_true]
218
+ rw [startMemory_input_update, startMemory_sum_update]
219
+ rfl
220
+
221
+ theorem headerTrace (again next : Label)
222
+ (atHeader : program again = readHeader again next)
223
+ (n sum : Nat) (suffix archive : List Bool)
224
+ (state : MachineLogCounter.State) (register : Option Bool) :
225
+ (MachineComposition.advance (TM2.step program))^[n + 1]
226
+ (some ⟨some again, (state, register),
227
+ startMemory (encodeWord n ++ suffix) archive (encodeWord sum)⟩) =
228
+ some ⟨some next, (state, none), startMemory suffix archive (encodeWord (n + sum))⟩ := by
229
+ induction n generalizing sum register with
230
+ | zero =>
231
+ simpa only [Nat.zero_add, Function.iterate_one, MachineComposition.advance_some] using
232
+ headerStep_zero again next atHeader suffix archive sum state register
233
+ | succ n ih =>
234
+ rw [Function.iterate_succ_apply, MachineComposition.advance_some]
235
+ rw [headerStep_succ again next atHeader n sum suffix archive state register]
236
+ simpa only [Nat.add_assoc, Nat.add_comm 1 sum] using ih (sum + 1) (some true)
237
+
238
+ def headerInTime (again next : Label)
239
+ (atHeader : program again = readHeader again next)
240
+ (n sum : Nat) (suffix archive : List Bool)
241
+ (state : MachineLogCounter.State) (register : Option Bool) :
242
+ StateTransition.EvalsToInTime (TM2.step program)
243
+ ⟨some again, (state, register), startMemory (encodeWord n ++ suffix) archive (encodeWord sum)⟩
244
+ (some ⟨some next, (state, none), startMemory suffix archive (encodeWord (n + sum))⟩)
245
+ (n + 1) where
246
+ steps := n + 1
247
+ evals_in_steps := headerTrace again next atHeader n sum suffix archive state register
248
+ steps_le_m := le_rfl
249
+
250
+ theorem initialMemory (word : List Bool) :
251
+ initList machine word =
252
+ ⟨some (.inr .copyFirst), initialState, startMemory word [] []⟩ := by
253
+ have ht : (initList machine word).stk = startMemory word [] [] := by
254
+ funext tape
255
+ cases tape with
256
+ | inl k => simp [initList, machine, startMemory]
257
+ | inr k =>
258
+ cases k <;> simp [initList, machine, startMemory, startExtra]
259
+ all_goals rfl
260
+ exact congrArg (TM2.Cfg.mk _ _) ht
261
+
262
+ theorem clockInitialMemory (word rest : List Bool) (sum : Nat) :
263
+ clockConfiguration (startExtra rest word) none
264
+ (initList MachineLogCounter.machine (encodeWord sum)) =
265
+ ⟨some (.inl 0), initialState, startMemory rest word (encodeWord sum)⟩ := by
266
+ have ht : clockTapes (initList MachineLogCounter.machine (encodeWord sum)).stk
267
+ (startExtra rest word) = startMemory rest word (encodeWord sum) := by
268
+ funext tape
269
+ cases tape with
270
+ | inl k =>
271
+ fin_cases k <;> simp [clockTapes, initList, MachineLogCounter.machine, startMemory]
272
+ all_goals rfl
273
+ | inr k => rfl
274
+ exact congrArg (TM2.Cfg.mk _ _) ht
275
+
276
+ def startInTime (n m : Nat) (rest : List Bool) :
277
+ StateTransition.EvalsToInTime machine.step
278
+ (initList machine (encodeWords [n, m] ++ rest))
279
+ (some (clockConfiguration (startExtra rest (encodeWords [n, m] ++ rest)) none
280
+ (initList MachineLogCounter.machine (encodeWord (n + m)))))
281
+ (2 * ((encodeWords [n, m] ++ rest).length + 1) + 1 + (n + 1) + (m + 1)) := by
282
+ let word := encodeWords [n, m] ++ rest
283
+ let b₀ := startMemory word [] []
284
+ let b₁ := startMemory word word []
285
+ let b₂ := startMemory word word (encodeWord 0)
286
+ have hc : Function.update b₀ (.inr .archive) (b₀ (.inr .input) ++ b₀ (.inr .archive)) = b₁ := by
287
+ funext tape
288
+ cases tape with
289
+ | inl k => simp [b₀, b₁, startMemory]
290
+ | inr k => cases k <;> simp [b₀, b₁, startMemory, startExtra]
291
+ let copy := MachineCopy.copyInTime (.inr ExtraTape.input) (.inr ExtraTape.archive)
292
+ (.inr ExtraTape.scratch) (by decide) (by decide) (by decide) false
293
+ (.inr ExtraLabel.copyFirst) (.inr ExtraLabel.copySecond) (some (.inr ExtraLabel.seed))
294
+ program rfl rfl b₀ rfl MachineLogCounter.initialState none
295
+ have copy' : StateTransition.EvalsToInTime (TM2.step program)
296
+ ⟨some (.inr .copyFirst), initialState, b₀⟩
297
+ (some ⟨some (.inr .seed), initialState, b₁⟩) (2 * (word.length + 1)) := by
298
+ have h := copy
299
+ rw [hc] at h
300
+ simpa only [initialState, show b₀ (.inr .input) = word from rfl] using h
301
+ have seed : StateTransition.EvalsToInTime (TM2.step program)
302
+ ⟨some (.inr .seed), initialState, b₁⟩
303
+ (some ⟨some (.inr .headerFirst), initialState, b₂⟩) 1 := by
304
+ refine ⟨⟨1, ?_⟩, le_rfl⟩
305
+ change some (TM2.stepAux (program (.inr .seed)) initialState b₁) = _
306
+ simp only [program, TM2.stepAux, b₁, startMemory]
307
+ rw [startMemory_sum_update]
308
+ rfl
309
+ have first := headerInTime (.inr .headerFirst) (.inr .headerSecond) rfl
310
+ n 0 (encodeWord m ++ rest) word MachineLogCounter.initialState none
311
+ have first' : StateTransition.EvalsToInTime (TM2.step program)
312
+ ⟨some (.inr .headerFirst), initialState, b₂⟩
313
+ (some ⟨some (.inr .headerSecond), initialState,
314
+ startMemory (encodeWord m ++ rest) word (encodeWord n)⟩) (n + 1) := by
315
+ simpa only [b₂, initialState, word, encodeWords, List.append_nil, List.append_assoc,
316
+ Nat.add_zero] using first
317
+ have second := headerInTime (.inr .headerSecond) (.inl 0) rfl
318
+ m n rest word MachineLogCounter.initialState none
319
+ have second' : StateTransition.EvalsToInTime (TM2.step program)
320
+ ⟨some (.inr .headerSecond), initialState,
321
+ startMemory (encodeWord m ++ rest) word (encodeWord n)⟩
322
+ (some ⟨some (.inl 0), initialState, startMemory rest word (encodeWord (n + m))⟩)
323
+ (m + 1) := by simpa only [initialState, Nat.add_comm m n] using second
324
+ let p₀ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ copy' seed
325
+ let p₁ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀ first'
326
+ let p := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₁ second'
327
+ rw [initialMemory, clockInitialMemory]
328
+ exact {
329
+ toEvalsTo := p.toEvalsTo
330
+ steps_le_m := by
331
+ have h := p.steps_le_m
332
+ change p.steps ≤ 2 * (word.length + 1) + 1 + (n + 1) + (m + 1)
333
+ omega
334
+ }
335
+
336
+ end MinUncutGames.Foundations.Complexity.GraphCounterModel
337
+
338
+ namespace MinUncutGames.Foundations.Complexity.GraphCounterFinish
339
+
340
+ open Turing GraphCounterModel
341
+
342
+ def extraTapes (rest original : List Bool) : ExtraTape → List Bool
343
+ | .input => rest
344
+ | .archive => original
345
+ | _ => []
346
+
347
+ def frame (input archive counter reversed output : List Bool) : Tape → List Bool
348
+ | .inl i => if i = 2 then counter else []
349
+ | .inr .input => input
350
+ | .inr .archive => archive
351
+ | .inr .scratch => reversed
352
+ | .inr .output => output
353
+
354
+ theorem trace_trans {α : Type*} (f : α → α) {a b : Nat} {x y z : α}
355
+ (first : f^[a] x = y) (second : f^[b] y = z) : f^[a + b] x = z := by
356
+ rw [Nat.add_comm, Function.iterate_add_apply, first, second]
357
+
358
+ theorem start_eq (counter rest original : List Bool) :
359
+ clockConfiguration (extraTapes rest original) none
360
+ (haltList MachineLogCounter.machine counter) =
361
+ ⟨some (.inr .clearInput), initialState, frame rest original counter [] []⟩ := by
362
+ rw [MachineLogCounter.haltList_eq]
363
+ unfold clockConfiguration
364
+ congr 1
365
+ funext tape
366
+ cases tape with
367
+ | inl i => fin_cases i <;> simp [clockTapes, frame, MachineLogCounter.configuration,
368
+ MachineLogCounter.rawTapes]
369
+ | inr k => cases k <;> rfl
370
+
371
+ theorem finish_eq (word : List Bool) :
372
+ (⟨none, initialState, frame [] [] [] [] word⟩ : TM2.Cfg Alphabet Label State) =
373
+ haltList machine word := by
374
+ unfold haltList
375
+ congr 1
376
+ funext tape
377
+ cases tape with
378
+ | inl i => simp [machine, frame]
379
+ | inr k =>
380
+ cases k <;> simp [machine, frame]
381
+ all_goals rfl
382
+
383
+ theorem drainTrace (rest original counter : List Bool) :
384
+ (MachineComposition.advance (TM2.step program))^[rest.length + 1]
385
+ (some ⟨some (.inr .clearInput), initialState, frame rest original counter [] []⟩) =
386
+ some ⟨some (.inr .clockCopy), initialState, frame [] original counter [] []⟩ := by
387
+ have h := (MachineDrain.drainInTime (Sum.inr ExtraTape.input) (Sum.inr ExtraLabel.clearInput)
388
+ (some (.inr .clockCopy)) program rfl (frame rest original counter [] [])
389
+ MachineLogCounter.initialState none).evals_in_steps
390
+ change (MachineComposition.advance (TM2.step program))^[rest.length + 1]
391
+ (some ⟨some (.inr .clearInput), initialState, frame rest original counter [] []⟩) = _ at h
392
+ have update : Function.update (frame rest original counter [] []) (.inr .input) [] =
393
+ frame [] original counter [] [] := by
394
+ funext tape
395
+ cases tape with
396
+ | inl i => simp [frame]
397
+ | inr k => cases k <;> simp [frame]
398
+ simpa only [update, initialState] using h
399
+
400
+ theorem clockCopyTrace (original counter : List Bool) :
401
+ (MachineComposition.advance (TM2.step program))^[counter.length + 1]
402
+ (some ⟨some (.inr .clockCopy), initialState, frame [] original counter [] []⟩) =
403
+ some ⟨some (.inr .archiveCopy), initialState, frame [] original [] counter.reverse []⟩ := by
404
+ have h := (Reduction.MachineTransfer.transferAtInTime (Sum.inl (2 : Fin 3))
405
+ (Sum.inr ExtraTape.scratch) (by decide) id false (.inr .clockCopy)
406
+ (some (.inr .archiveCopy)) program rfl (frame [] original counter [] [])
407
+ MachineLogCounter.initialState none).evals_in_steps
408
+ change (MachineComposition.advance (TM2.step program))^[counter.length + 1]
409
+ (some ⟨some (.inr .clockCopy), initialState, frame [] original counter [] []⟩) = _ at h
410
+ have update : Reduction.MachineTransfer.tapesAt (Sum.inl (2 : Fin 3))
411
+ (Sum.inr ExtraTape.scratch) (frame [] original counter [] []) []
412
+ ((frame [] original counter [] [] (.inl 2)).reverse.map id ++
413
+ frame [] original counter [] [] (.inr .scratch)) =
414
+ frame [] original [] counter.reverse [] := by
415
+ funext tape
416
+ cases tape with
417
+ | inl i => fin_cases i <;> simp [Reduction.MachineTransfer.tapesAt, frame]
418
+ | inr k => cases k <;> simp [Reduction.MachineTransfer.tapesAt, frame]
419
+ simpa only [update, initialState] using h
420
+
421
+ theorem archiveCopyTrace (original counter : List Bool) :
422
+ (MachineComposition.advance (TM2.step program))^[original.length + 1]
423
+ (some ⟨some (.inr .archiveCopy), initialState, frame [] original [] counter.reverse []⟩) =
424
+ some ⟨some (.inr .finalReverse), initialState,
425
+ frame [] [] [] (original.reverse ++ counter.reverse) []⟩ := by
426
+ have h := (Reduction.MachineTransfer.transferAtInTime (Sum.inr ExtraTape.archive)
427
+ (Sum.inr ExtraTape.scratch) (by decide) id false (.inr .archiveCopy)
428
+ (some (.inr .finalReverse)) program rfl (frame [] original [] counter.reverse [])
429
+ MachineLogCounter.initialState none).evals_in_steps
430
+ change (MachineComposition.advance (TM2.step program))^[original.length + 1]
431
+ (some ⟨some (.inr .archiveCopy), initialState, frame [] original [] counter.reverse []⟩) = _ at h
432
+ have update : Reduction.MachineTransfer.tapesAt (Sum.inr ExtraTape.archive)
433
+ (Sum.inr ExtraTape.scratch) (frame [] original [] counter.reverse []) []
434
+ ((frame [] original [] counter.reverse [] (.inr .archive)).reverse.map id ++
435
+ frame [] original [] counter.reverse [] (.inr .scratch)) =
436
+ frame [] [] [] (original.reverse ++ counter.reverse) [] := by
437
+ funext tape
438
+ cases tape with
439
+ | inl i => simp [Reduction.MachineTransfer.tapesAt, frame]
440
+ | inr k => cases k <;> simp [Reduction.MachineTransfer.tapesAt, frame]
441
+ simpa only [update, initialState] using h
442
+
443
+ theorem reverseTrace (original counter : List Bool) :
444
+ (MachineComposition.advance (TM2.step program))^[original.length + counter.length + 1]
445
+ (some ⟨some (.inr .finalReverse), initialState,
446
+ frame [] [] [] (original.reverse ++ counter.reverse) []⟩) =
447
+ some (haltList machine (counter ++ original)) := by
448
+ have h := (Reduction.MachineTransfer.transferAtInTime (Sum.inr ExtraTape.scratch)
449
+ (Sum.inr ExtraTape.output) (by decide) id false (.inr .finalReverse) none program rfl
450
+ (frame [] [] [] (original.reverse ++ counter.reverse) []) MachineLogCounter.initialState none).evals_in_steps
451
+ change (MachineComposition.advance (TM2.step program))^[
452
+ (original.reverse ++ counter.reverse).length + 1]
453
+ (some ⟨some (.inr .finalReverse), initialState,
454
+ frame [] [] [] (original.reverse ++ counter.reverse) []⟩) = _ at h
455
+ have update : Reduction.MachineTransfer.tapesAt (Sum.inr ExtraTape.scratch)
456
+ (Sum.inr ExtraTape.output) (frame [] [] [] (original.reverse ++ counter.reverse) []) []
457
+ ((frame [] [] [] (original.reverse ++ counter.reverse) [] (.inr .scratch)).reverse.map id ++
458
+ frame [] [] [] (original.reverse ++ counter.reverse) [] (.inr .output)) =
459
+ frame [] [] [] [] (counter ++ original) := by
460
+ funext tape
461
+ cases tape with
462
+ | inl i => simp [Reduction.MachineTransfer.tapesAt, frame]
463
+ | inr k => cases k <;> simp [Reduction.MachineTransfer.tapesAt, frame]
464
+ rw [update] at h
465
+ rw [← finish_eq]
466
+ simpa only [List.length_append, List.length_reverse, initialState] using! h
467
+
468
+ theorem finishTrace (counter rest original : List Bool) :
469
+ (MachineComposition.advance (TM2.step program))^[
470
+ rest.length + 2 * counter.length + 2 * original.length + 4]
471
+ (some (clockConfiguration (extraTapes rest original) none
472
+ (haltList MachineLogCounter.machine counter))) =
473
+ some (haltList machine (counter ++ original)) := by
474
+ rw [start_eq]
475
+ have total := trace_trans _
476
+ (trace_trans _ (trace_trans _ (drainTrace rest original counter)
477
+ (clockCopyTrace original counter)) (archiveCopyTrace original counter))
478
+ (reverseTrace original counter)
479
+ simpa only [show rest.length + 1 + (counter.length + 1) + (original.length + 1) +
480
+ (original.length + counter.length + 1) =
481
+ rest.length + 2 * counter.length + 2 * original.length + 4 by omega] using total
482
+
483
+ def finishInTime (counter rest original : List Bool) :
484
+ StateTransition.EvalsToInTime (TM2.step program)
485
+ (clockConfiguration (extraTapes rest original) none (haltList MachineLogCounter.machine counter))
486
+ (some (haltList machine (counter ++ original)))
487
+ (rest.length + 2 * counter.length + 2 * original.length + 4) where
488
+ steps := rest.length + 2 * counter.length + 2 * original.length + 4
489
+ evals_in_steps := finishTrace counter rest original
490
+ steps_le_m := le_rfl
491
+
492
+ end MinUncutGames.Foundations.Complexity.GraphCounterFinish
493
+
494
+ namespace MinUncutGames.Foundations.Complexity.GraphCounterPrefix
495
+
496
+ open Turing PCP GraphCounterModel GraphCounterFinish
497
+
498
+ def rawOutput (n m : Nat) (rest : List Bool) : List Bool :=
499
+ encodeWord ((n + m).log2 + 1) ++ (encodeWords [n, m] ++ rest)
500
+
501
+ def rawInTime (n m : Nat) (rest : List Bool) :
502
+ TM2OutputsInTime machine (encodeWords [n, m] ++ rest) (some (rawOutput n m rest))
503
+ (20 * (encodeWords [n, m] ++ rest).length + 30) := by
504
+ let original := encodeWords [n, m] ++ rest
505
+ let start := startInTime n m rest
506
+ let clock := clockInTime (extraTapes rest original) none (n + m)
507
+ let finish := finishInTime (encodeWord ((n + m).log2 + 1)) rest original
508
+ have start' : StateTransition.EvalsToInTime (TM2.step program)
509
+ (initList machine original)
510
+ (some (clockConfiguration (extraTapes rest original) none
511
+ (initList MachineLogCounter.machine (encodeWord (n + m)))))
512
+ (2 * (original.length + 1) + 1 + (n + 1) + (m + 1)) := start
513
+ let first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ start' clock
514
+ let total := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first finish
515
+ refine { toEvalsTo := total.toEvalsTo, steps_le_m := ?_ }
516
+ have bound := total.steps_le_m
517
+ have hlog := Nat.log2_le_self (n + m)
518
+ have hlength : original.length = n + m + 2 + rest.length := by
519
+ simp only [original, List.length_append, encodeWords, encodeWord_length, List.length_nil]
520
+ omega
521
+ simp only [encodeWord_length] at bound
522
+ change total.steps ≤ 20 * original.length + 30
523
+ omega
524
+
525
+ def count (table : GraphTables.Table) : Nat := (table.vertices + table.darts).log2 + 1
526
+
527
+ def output (table : GraphTables.Table) : List Bool :=
528
+ encodeWord (count table) ++ GraphTables.tableBits table
529
+
530
+ def rowsBits (table : GraphTables.Table) : List Bool :=
531
+ encodeWords ((GraphTables.rowList table).flatMap GraphTables.rowWords)
532
+
533
+ theorem tableBits_decomposition (table : GraphTables.Table) :
534
+ GraphTables.tableBits table = encodeWords [table.vertices, table.darts] ++ rowsBits table :=
535
+ encodeWords_append _ _
536
+
537
+ def outputsInTime (table : GraphTables.Table) :
538
+ TM2OutputsInTime machine (GraphTables.tableBits table) (some (output table))
539
+ (20 * (GraphTables.tableBits table).length + 30) := by
540
+ have run := rawInTime table.vertices table.darts (rowsBits table)
541
+ simpa only [rawOutput, output, count, tableBits_decomposition] using run
542
+
543
+ noncomputable def computableInPolyTime :
544
+ TM2ComputableInPolyTime GraphTables.tableBits id output where
545
+ tm := machine
546
+ inputAlphabet := Equiv.refl Bool
547
+ outputAlphabet := Equiv.refl Bool
548
+ time := 20 * Polynomial.X + 30
549
+ outputsFun table := by
550
+ change TM2OutputsInTime machine ((GraphTables.tableBits table).map id)
551
+ (some ((output table).map id))
552
+ ((20 * Polynomial.X + 30 : Polynomial Nat).eval (GraphTables.tableBits table).length)
553
+ have input_eq : @List.map (machine.Γ machine.k₀) (machine.Γ machine.k₀) id
554
+ (GraphTables.tableBits table) = GraphTables.tableBits table := List.map_id _
555
+ have output_eq : @List.map (machine.Γ machine.k₁) (machine.Γ machine.k₁) id
556
+ (output table) = output table := List.map_id _
557
+ rw [input_eq, output_eq]
558
+ simpa only [Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_ofNat,
559
+ Polynomial.eval_X] using outputsInTime table
560
+
561
+ end MinUncutGames.Foundations.Complexity.GraphCounterPrefix
562
+
563
+ end OAI
lean/OAI/Computability/MinUncut/Games/GraphIterationBounds.lean ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.PCP.TableIteration
3
+ import OAI.Computability.MinUncut.Games.GraphCounterModel
4
+ import OAI.Computability.MinUncut.Machines.PCPIterationMachine
5
+
6
+ namespace OAI
7
+
8
+ section
9
+ namespace MinUncutGames.Foundations.Complexity.GraphIterationBounds
10
+
11
+ open PCP RoundTables
12
+
13
+ def inputBits (input : Input) : List Bool := GraphTables.tableBits input.val
14
+
15
+ def countedBits (input : Input) : List Bool := GraphCounterPrefix.output input.val
16
+
17
+ def words (H : BaseTable) (input : Input) (i : Nat) : List Bool :=
18
+ GraphTables.tableBits (TableIteration.runTables H i input.val)
19
+
20
+ def count (input : Input) : Nat := GraphCounterPrefix.count input.val
21
+
22
+ noncomputable def lengthPolynomial : Polynomial Nat :=
23
+ (GraphTableComplexity.encodingPolynomial 64).comp (PCPIterationMachine.sizePolynomial sizeFactor)
24
+
25
+ theorem inputBits_le_countedBits (input : Input) : (inputBits input).length ≤ (countedBits input).length := by
26
+ simp only [inputBits, countedBits, GraphCounterPrefix.output, List.length_append]
27
+ omega
28
+
29
+ theorem size_le_inputBits (input : Input) : size input ≤ (inputBits input).length := by
30
+ have h := GraphTableComplexity.size_add_two_le_bits input.val
31
+ unfold size inputBits
32
+ omega
33
+
34
+ theorem count_le (input : Input) : count input ≤ (countedBits input).length + 1 :=
35
+ (PCPIterationMachine.rounds_le (size input)).trans
36
+ (Nat.add_le_add_right ((size_le_inputBits input).trans (inputBits_le_countedBits input)) 1)
37
+
38
+ theorem intermediate_size (H : BaseTable) (input : Input) (i : Nat) (hi : i ≤ count input) :
39
+ size (TableIteration.run H i input) ≤ PCPIterationMachine.sizeEnvelope sizeFactor (size input) := by
40
+ apply PCPIterationMachine.semanticSize_bound
41
+ (fun j => size (TableIteration.run H j input)) sizeFactor (size input)
42
+ sizeFactor_positive (Nat.le_succ _) _ i hi
43
+ intro j _
44
+ exact step_size H (TableIteration.run H j input)
45
+
46
+ theorem intermediate_bits (H : BaseTable) (input : Input) (i : Nat) (hi : i ≤ count input) :
47
+ (words H input i).length ≤ lengthPolynomial.eval (countedBits input).length := by
48
+ have hsize := intermediate_size H input i hi
49
+ have hinput := (size_le_inputBits input).trans (inputBits_le_countedBits input)
50
+ have heval := MachineComposition.natPolynomial_eval_mono
51
+ (PCPIterationMachine.sizePolynomial sizeFactor) hinput
52
+ rw [PCPIterationMachine.sizePolynomial_eval, PCPIterationMachine.sizePolynomial_eval] at heval
53
+ have hs := hsize.trans heval
54
+ have htable : (TableIteration.runTables H i input.val).vertices +
55
+ (TableIteration.runTables H i input.val).darts ≤
56
+ PCPIterationMachine.sizeEnvelope sizeFactor (countedBits input).length := by
57
+ rw [← TableIteration.run_val]
58
+ exact hs
59
+ rw [lengthPolynomial, Polynomial.eval_comp, PCPIterationMachine.sizePolynomial_eval]
60
+ exact GraphTableComplexity.bits_le_of_size_le _ htable
61
+
62
+ noncomputable def runtimePolynomial (bodyTime : Polynomial Nat) : Polynomial Nat :=
63
+ (Polynomial.X + 1) * (bodyTime.comp lengthPolynomial + 2 * lengthPolynomial + 4) +
64
+ 2 * lengthPolynomial + 4
65
+
66
+ theorem runtimePolynomial_eval (bodyTime : Polynomial Nat) (N : Nat) :
67
+ (runtimePolynomial bodyTime).eval N =
68
+ (N + 1) * (bodyTime.eval (lengthPolynomial.eval N) + 2 * lengthPolynomial.eval N + 4) +
69
+ 2 * lengthPolynomial.eval N + 4 := by
70
+ simp only [runtimePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_X,
71
+ Polynomial.eval_one, Polynomial.eval_ofNat, Polynomial.eval_comp]
72
+
73
+ end MinUncutGames.Foundations.Complexity.GraphIterationBounds
74
+
75
+ end
76
+
77
+ end OAI
lean/OAI/Computability/MinUncut/Games/HintSections.lean ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.OuterSampling
3
+ import OAI.Computability.MinUncut.Estimates.PatchExpectation
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ noncomputable section
9
+ open scoped BigOperators
10
+ namespace MinUncut.Outer
11
+ open MinUncut.Inner
12
+ attribute [local instance] Classical.propDecidable
13
+ variable {Name I S : Type*} [Fintype Name] [Fintype I] [Fintype S] [Nonempty S]
14
+
15
+ def sampledEquations (equations : S → Equation Name) (w : I → S × Fin 3) : I → Equation Name :=
16
+ fun j => equations (w j).1
17
+
18
+ def sampledPositions (w : I → S × Fin 3) : I → Fin 3 := fun j => (w j).2
19
+
20
+ omit [Fintype Name] [Fintype I] [Fintype S] [Nonempty S] in
21
+ lemma sampledEquations_patch (equations : S → Equation Name) (A : I → Prop)
22
+ (bg : I → S × Fin 3) (w : {i // A i} → S × Fin 3) :
23
+ sampledEquations equations (patch A bg w)=
24
+ patch A (sampledEquations equations bg) (sampledEquations equations w) :=
25
+ patch_comp A bg w (fun x => equations x.1)
26
+
27
+ omit [Fintype Name] [Fintype I] [Fintype S] [Nonempty S] in
28
+ lemma sampledPositions_patch (A : I → Prop)
29
+ (bg : I → S × Fin 3) (w : {i // A i} → S × Fin 3) :
30
+ sampledPositions (patch A bg w)=
31
+ patch A (sampledPositions bg) (sampledPositions w) := patch_comp A bg w Prod.snd
32
+
33
+ theorem hint_section_bound (equations : S → Equation Name)
34
+ (hsound : ∀ s : Name → F₂, equationFraction equations s ≤ 3/4)
35
+ {q : ℕ} (strategy : HintedStrategy Name I q)
36
+ (A : I → Prop) (hidden : I → Bool) (hA : ∀ i, A i → hidden i=true)
37
+ (c : HintCoefficients I q) (hzero : ∀ k i, A i → (c k).2.1 i=0)
38
+ (bg : I → S × Fin 3) :
39
+ (𝔼 w : {i // A i} → S × Fin 3,
40
+ if hintedWins strategy (sampledEquations equations (patch A bg w)) hidden
41
+ (sampledPositions (patch A bg w)) c then (1 : ℝ) else 0) ≤
42
+ repetitionRate ^ Fintype.card {i // A i} := by
43
+ classical
44
+ obtain ⟨a,b,hsim⟩ := active_simulation strategy A hidden hA c hzero
45
+ (sampledEquations equations bg) (sampledPositions bg)
46
+ have hrep := ordinary_repetition_on equations hsound a b
47
+ apply le_trans (b := (𝔼 w : {i // A i} → S × Fin 3,
48
+ if (∀ j, ordinaryAccepts (equations (w j).1)
49
+ ((equations (w j).1).names (w j).2)
50
+ (a (fun i => equations (w i).1) j)
51
+ (b (fun i => (equations (w i).1).names (w i).2) j)=true)
52
+ then (1 : ℝ) else 0)) ?_ (by
53
+ convert hrep using 1; congr 1
54
+ exact Finset.ext (by intro x; simp))
55
+ refine Finset.expect_le_expect (fun w _ => ?_)
56
+ split_ifs with hw hr hr
57
+ · rfl
58
+ · exfalso
59
+ apply hr
60
+ have hwin := hw
61
+ rw [sampledEquations_patch,sampledPositions_patch] at hwin
62
+ exact hsim (sampledEquations equations w) (sampledPositions w) hwin
63
+ · norm_num
64
+ · rfl
65
+
66
+ theorem hint_fixed_coefficients_bound (equations : S → Equation Name)
67
+ (hsound : ∀ s : Name → F₂, equationFraction equations s ≤ 3/4)
68
+ {q : ℕ} (strategy : HintedStrategy Name I q)
69
+ (A : I → Prop) (hidden : I → Bool) (hA : ∀ i, A i → hidden i=true)
70
+ (c : HintCoefficients I q) (hzero : ∀ k i, A i → (c k).2.1 i=0) :
71
+ (𝔼 w : I → S × Fin 3,
72
+ if hintedWins strategy (sampledEquations equations w) hidden
73
+ (sampledPositions w) c then (1 : ℝ) else 0) ≤
74
+ repetitionRate ^ Fintype.card {i // A i} :=
75
+ expect_le_of_active_sections A _ _
76
+ (hint_section_bound equations hsound strategy A hidden hA c hzero)
77
+
78
+ end MinUncut.Outer
79
+
80
+ end
81
+ end
82
+
83
+ end OAI
lean/OAI/Computability/MinUncut/Games/HintSimulation.lean ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.Sampling
3
+
4
+ namespace OAI
5
+
6
+ noncomputable section
7
+ open scoped BigOperators
8
+ namespace MinUncut.Outer
9
+ open MinUncut.Inner
10
+ attribute [local instance] Classical.propDecidable
11
+ variable {Name I : Type*} [Fintype I]
12
+
13
+ abbrev HintCoefficients (I : Type*) (q : ℕ) :=
14
+ Fin q → (F₂ × ((I → F₂) × (I → Module.Dual F₂ Triple)))
15
+
16
+ def secondHints {q : ℕ} (V : I → SecondQuestion Name) (c : HintCoefficients I q) :
17
+ Fin q → Forms (SecondAlphabet V) := fun k => hintGenerator V (c k)
18
+
19
+ def firstHints {q : ℕ} (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3)
20
+ (c : HintCoefficients I q) : Fin q → Forms (FirstAlphabet U) :=
21
+ fun k => formPullback (projection U hidden pos) (secondHints (secondQuestion U hidden pos) c k)
22
+
23
+ structure HintedStrategy (Name I : Type*) [Fintype I] (q : ℕ) where
24
+ first : (U : I → Equation Name) → (Fin q → Forms (FirstAlphabet U)) → FirstAlphabet U
25
+ second : (V : I → SecondQuestion Name) → (Fin q → Forms (SecondAlphabet V)) → SecondAlphabet V
26
+
27
+ def hintedWins {q : ℕ} (strategy : HintedStrategy Name I q)
28
+ (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3)
29
+ (c : HintCoefficients I q) : Prop :=
30
+ projection U hidden pos (strategy.first U (firstHints U hidden pos c)) =
31
+ strategy.second (secondQuestion U hidden pos) (secondHints (secondQuestion U hidden pos) c)
32
+
33
+ def patch {X : Type*} (A : I → Prop) (background : I → X) (active : {i // A i} → X) : I → X :=
34
+ fun i => if h : A i then active ⟨i,h⟩ else background i
35
+
36
+ omit [Fintype I] in
37
+ @[simp] lemma patch_active {X : Type*} (A : I → Prop) (background : I → X)
38
+ (active : {i // A i} → X) (i : {i // A i}) : patch A background active i = active i := by
39
+ simp [patch,i.property]
40
+
41
+ omit [Fintype I] in
42
+ @[simp] lemma patch_inactive {X : Type*} (A : I → Prop) (background : I → X)
43
+ (active : {i // A i} → X) (i : I) (hi : ¬A i) : patch A background active i = background i := by
44
+ simp [patch,hi]
45
+
46
+ omit [Fintype I] in
47
+ lemma patch_comp {X Y : Type*} (A : I → Prop) (background : I → X)
48
+ (active : {i // A i} → X) (f : X → Y) :
49
+ (fun i => f (patch A background active i)) = patch A (fun i => f (background i)) (fun i => f (active i)) := by
50
+ funext i
51
+ by_cases h : A i <;> simp [patch,h]
52
+
53
+ def slotZero (v : SecondQuestion Name) : Fin (secondSlotCount v) :=
54
+ ⟨0,by cases v <;> exact Nat.zero_lt_succ _⟩
55
+
56
+ def readBit (V : I → SecondQuestion Name) (a : SecondAlphabet V) (i : I) : F₂ :=
57
+ a i (slotZero (V i))
58
+
59
+ omit [Fintype I] in
60
+ lemma projection_hidden_bit (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3)
61
+ (a : FirstAlphabet U) (i : I) (hi : hidden i=true) :
62
+ readBit (secondQuestion U hidden pos) (projection U hidden pos a) i=(a i).val (pos i) := by
63
+ change (slotProjection (U i) (hidden i) (pos i) (a i))
64
+ (slotZero (slotQuestion (U i) (hidden i) (pos i)))=_
65
+ rw [hi]
66
+ rfl
67
+
68
+ lemma firstHints_position_independent {q : ℕ} (U : I → Equation Name) (hidden : I → Bool)
69
+ (pos pos' : I → Fin 3) (c : HintCoefficients I q)
70
+ (h : ∀ k j, hidden j=true → pos j≠pos' j → (c k).2.1 j=0) :
71
+ firstHints U hidden pos c=firstHints U hidden pos' c := by
72
+ funext k
73
+ exact pulledHint_independent_active U hidden pos pos' _ _ _ (h k)
74
+
75
+ lemma ordinary_accepts_of_valid_coordinate (E : Equation Name) (a : alphabet E)
76
+ (p : Fin 3) (b : F₂) (he : a.val p=b) :
77
+ ordinaryAccepts E (E.names p) a.val b=true := by
78
+ apply decide_eq_true
79
+ refine ⟨a.property,?_⟩
80
+ intro p' hp'
81
+ exact (a.property.2 p' p hp').trans he
82
+
83
+ omit [Fintype I] in
84
+
85
+ lemma secondQuestion_patch (A : I → Prop) (hidden : I → Bool)
86
+ (hA : ∀ i, A i → hidden i=true) (bgU : I → Equation Name) (bgp : I → Fin 3)
87
+ (U : {i // A i} → Equation Name) (p : {i // A i} → Fin 3) :
88
+ secondQuestion (patch A bgU U) hidden (patch A bgp p) =
89
+ patch A (secondQuestion bgU hidden bgp) (fun i => Sum.inl ((U i).names (p i))) := by
90
+ funext i
91
+ by_cases hi : A i
92
+ · simp [patch,secondQuestion,slotQuestion,hA i hi,hi]
93
+ · simp [patch,secondQuestion,hi]
94
+
95
+ end MinUncut.Outer
96
+
97
+ namespace MinUncut.Outer
98
+ open MinUncut.Inner
99
+ attribute [local instance] Classical.propDecidable
100
+ variable {Name I : Type*} [Fintype I]
101
+
102
+ theorem active_simulation {q : ℕ} (strategy : HintedStrategy Name I q)
103
+ (A : I → Prop) (hidden : I → Bool) (hA : ∀ i, A i → hidden i=true)
104
+ (c : HintCoefficients I q) (hzero : ∀ k i, A i → (c k).2.1 i=0)
105
+ (bgU : I → Equation Name) (bgp : I → Fin 3) :
106
+ ∃ (a : ({i // A i} → Equation Name) → {i // A i} → Triple)
107
+ (b : ({i // A i} → Name) → {i // A i} → F₂),
108
+ ∀ (U : {i // A i} → Equation Name) (p : {i // A i} → Fin 3),
109
+ hintedWins strategy (patch A bgU U) hidden (patch A bgp p) c →
110
+ ∀ j, ordinaryAccepts (U j) ((U j).names (p j)) (a U j)
111
+ (b (fun i => (U i).names (p i)) j)=true := by
112
+ classical
113
+ let p₀ : I → Fin 3 := patch A bgp (fun _ => 0)
114
+ let first (U : {i // A i} → Equation Name) : FirstAlphabet (patch A bgU U) :=
115
+ strategy.first (patch A bgU U) (firstHints (patch A bgU U) hidden p₀ c)
116
+ let V (y : {i // A i} → Name) : I → SecondQuestion Name :=
117
+ patch A (secondQuestion bgU hidden bgp) (fun i => Sum.inl (y i))
118
+ let second (y : {i // A i} → Name) : SecondAlphabet (V y) :=
119
+ strategy.second (V y) (secondHints (V y) c)
120
+ let a := fun U (j : {i // A i}) => (first U j).val
121
+ let b := fun y (j : {i // A i}) => readBit (V y) (second y) j
122
+ refine ⟨a,b,?_⟩
123
+ intro U p hwin j
124
+ have hints : firstHints (patch A bgU U) hidden (patch A bgp p) c =
125
+ firstHints (patch A bgU U) hidden p₀ c := by
126
+ apply firstHints_position_independent
127
+ intro k i _ hdiff
128
+ apply hzero k i
129
+ by_contra hi
130
+ exact hdiff (by simp [p₀,patch,hi])
131
+ have hv : secondQuestion (patch A bgU U) hidden (patch A bgp p) =
132
+ V (fun i => (U i).names (p i)) := secondQuestion_patch A hidden hA bgU bgp U p
133
+ unfold hintedWins at hwin
134
+ rw [hints] at hwin
135
+ have hb := congrArg (fun z =>
136
+ readBit (secondQuestion (patch A bgU U) hidden (patch A bgp p)) z j) hwin
137
+ rw [projection_hidden_bit _ _ _ _ _ (hA j j.property)] at hb
138
+ have hcoord : a U j (p j)=b (fun i => (U i).names (p i)) j := by
139
+ simp only [patch_active] at hb
140
+ rw [hv] at hb
141
+ exact hb
142
+ have hvalid : Valid (U j) (a U j) := by
143
+ have hv' : Valid (patch A bgU U j) (a U j) := (first U j).property
144
+ simpa only [patch_active] using hv'
145
+ apply decide_eq_true
146
+ refine ⟨hvalid,?_⟩
147
+ intro p' hp'
148
+ exact (hvalid.2 p' (p j) hp').trans hcoord
149
+
150
+ end MinUncut.Outer
151
+
152
+ end
153
+
154
+ end OAI
lean/OAI/Computability/MinUncut/Games/HintSoundness.lean ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.HintSections
3
+ import OAI.Computability.MinUncut.Estimates.CoefficientMoments
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ noncomputable section
9
+ open scoped BigOperators
10
+ namespace MinUncut.Outer
11
+ open MinUncut.Inner
12
+ attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype
13
+ variable {Name I S : Type*} [Fintype Name] [Fintype I] [Fintype S] [Nonempty S]
14
+
15
+ def hintedAcceptance {q : ℕ} (strategy : HintedStrategy Name I q)
16
+ (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3)
17
+ (L : Fin q → Forms (SecondAlphabet (secondQuestion U hidden pos))) : Prop :=
18
+ projection U hidden pos
19
+ (strategy.first U (fun k => formPullback (projection U hidden pos) (L k))) =
20
+ strategy.second (secondQuestion U hidden pos) L
21
+
22
+ omit [Fintype Name] [Fintype S] [Nonempty S] in
23
+ lemma hintedAcceptance_generated {q : ℕ} (strategy : HintedStrategy Name I q)
24
+ (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3)
25
+ (c : HintCoefficients I q) :
26
+ hintedAcceptance strategy U hidden pos
27
+ (hintTupleGenerator (secondQuestion U hidden pos) q c) ↔
28
+ hintedWins strategy U hidden pos c := Iff.rfl
29
+
30
+ theorem shared_hint_soundness (equations : S → Equation Name)
31
+ (hsound : ∀ s : Name → F₂, equationFraction equations s ≤ 3/4)
32
+ {q : ℕ} (strategy : HintedStrategy Name I q) (hidden : I → Bool) :
33
+ (𝔼 w : I → S × Fin 3,
34
+ 𝔼 L : Fin q → Forms (SecondAlphabet
35
+ (secondQuestion (sampledEquations equations w) hidden (sampledPositions w))),
36
+ if hintedAcceptance strategy (sampledEquations equations w) hidden
37
+ (sampledPositions w) L then (1 : ℝ) else 0) ≤
38
+ hintRate q ^ Fintype.card {i // hidden i=true} := by
39
+ classical
40
+ have hsample (w : I → S × Fin 3) :
41
+ (𝔼 L : Fin q → Forms (SecondAlphabet
42
+ (secondQuestion (sampledEquations equations w) hidden (sampledPositions w))),
43
+ if hintedAcceptance strategy (sampledEquations equations w) hidden
44
+ (sampledPositions w) L then (1 : ℝ) else 0) =
45
+ (𝔼 c : HintCoefficients I q,
46
+ if hintedWins strategy (sampledEquations equations w) hidden
47
+ (sampledPositions w) c then (1 : ℝ) else 0) := by
48
+ exact (uniform_hintTupleGenerator _ q
49
+ (fun L => if hintedAcceptance strategy (sampledEquations equations w) hidden
50
+ (sampledPositions w) L then (1 : ℝ) else 0)).symm
51
+ simp_rw [hsample]
52
+ rw [Finset.expect_comm]
53
+ calc
54
+ _ ≤ 𝔼 c : HintCoefficients I q,
55
+ repetitionRate ^ Fintype.card {i // Active hidden (coefficientVectors q c) i} := by
56
+ apply Finset.expect_le_expect
57
+ intro c _
58
+ apply hint_fixed_coefficients_bound equations hsound strategy
59
+ (Active hidden (coefficientVectors q c)) hidden (fun _ hi => hi.1) c
60
+ intro k i hi
61
+ exact congrFun hi.2 k
62
+ _ = _ := coefficient_active_expect q hidden
63
+
64
+ lemma shared_hint_rate_vanishes (q : ℕ) {ε : ℝ} (hε : 0<ε) :
65
+ ∃ n : ℕ, hintRate q ^ n < ε := by
66
+ exact (tendsto_pow_atTop_nhds_zero_of_lt_one (hintRate_nonnegative q)
67
+ (hintRate_lt_one q)).eventually (gt_mem_nhds hε) |>.exists
68
+
69
+ end MinUncut.Outer
70
+
71
+ end
72
+ end
73
+
74
+ end OAI
lean/OAI/Computability/MinUncut/Games/IncidenceProbability.lean ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.SamplerAssembly
3
+ import OAI.Computability.MinUncut.Games.Actual
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ namespace MinUncutGames.Reduction.IncidenceProbability
9
+
10
+ variable {Variable : Type*} {Index : Type*} {I : Type*} {Coin : Type*}
11
+
12
+ open Incidence
13
+ open scoped BigOperators
14
+
15
+ theorem sum_bool_indicator_eq_count_ofFn {n : Nat} (p : Fin n → Bool) :
16
+ (∑ i, if p i then (1 : ℚ) else 0) = ((List.ofFn p).countP id : ℚ) := by
17
+ induction n with
18
+ | zero => simp
19
+ | succ n ih =>
20
+ rw [Fin.sum_univ_succ, List.ofFn_succ, List.countP_cons, ih]
21
+ cases p 0 <;> simp [add_comm]
22
+
23
+ theorem expect_bool_indicator_eq_count_ofFn {n : Nat} (p : Fin n → Bool) :
24
+ Finset.univ.expect (fun i : Fin n => if p i then (1 : ℚ) else 0) =
25
+ ((List.ofFn p).countP id : ℚ) / n := by
26
+ rw [Fintype.expect_eq_sum_div_card, sum_bool_indicator_eq_count_ofFn]
27
+ simp
28
+
29
+ def slotOfFin (i : Fin 3) : Slot :=
30
+ if i = 0 then .first else if i = 1 then .second else .third
31
+
32
+ def slotPredicate (e : Equation Variable) (alice : Triple) (g : Variable → Bool)
33
+ (slot : Fin 3) : Prop :=
34
+ parity alice = e.rhs ∧
35
+ bitAt alice (slotOfFin slot) = g (nameAt e (slotOfFin slot))
36
+
37
+ instance (e : Equation Variable) (alice : Triple) (g : Variable → Bool) (slot : Fin 3) :
38
+ Decidable (slotPredicate e alice g slot) := inferInstanceAs (Decidable (_ ∧ _))
39
+
40
+ def slotAcceptance (e : Equation Variable) (alice : Triple) (g : Variable → Bool)
41
+ (slot : Fin 3) : ℚ := if slotPredicate e alice g slot then 1 else 0
42
+
43
+ theorem slot_predicate_is_question_predicate (e : Equation Variable)
44
+ (h12 : e.first ≠ e.second) (h13 : e.first ≠ e.third)
45
+ (h23 : e.second ≠ e.third) (alice : Triple) (g : Variable → Bool) (slot : Fin 3) :
46
+ slotPredicate e alice g slot ↔
47
+ questionPredicate e (nameAt e (slotOfFin slot)) alice
48
+ (g (nameAt e (slotOfFin slot))) := by
49
+ exact (question_predicate_at_slot e h12 h13 h23 alice _ (slotOfFin slot)).symm
50
+
51
+ theorem sum_slot_acceptance (e : Equation Variable) (alice : Triple)
52
+ (g : Variable → Bool) :
53
+ ∑ slot : Fin 3, slotAcceptance e alice g slot =
54
+ (acceptedSlots alice (bobTriple g e) e.rhs : ℚ) := by
55
+ rw [Fin.sum_univ_three]
56
+ by_cases valid : parity alice = e.rhs
57
+ · simp only [slotAcceptance, slotPredicate, valid, true_and, slotOfFin,
58
+ show (1 : Fin 3) ≠ 0 from by decide,
59
+ show (2 : Fin 3) ≠ 0 from by decide, show (2 : Fin 3) ≠ 1 from by decide,
60
+ ↓reduceIte, nameAt, bitAt, acceptedSlots, matchingSlots, bobTriple,
61
+ Nat.cast_add]
62
+ split_ifs <;> simp_all
63
+ · simp [slotAcceptance, slotPredicate, valid, acceptedSlots]
64
+
65
+ theorem expect_slot_acceptance (e : Equation Variable) (alice : Triple)
66
+ (g : Variable → Bool) :
67
+ Finset.univ.expect (slotAcceptance e alice g) =
68
+ (acceptedSlots alice (bobTriple g e) e.rhs : ℚ) / 3 := by
69
+ rw [Fintype.expect_eq_sum_div_card, sum_slot_acceptance]
70
+ simp
71
+
72
+ variable [Fintype Index]
73
+
74
+ def acceptanceProbability (equations : Index → Equation Variable)
75
+ (alice : Index → Triple) (g : Variable → Bool) : ℚ :=
76
+ Finset.univ.expect (fun q : Index × Fin 3 =>
77
+ slotAcceptance (equations q.1) (alice q.1) g q.2)
78
+
79
+ def failureProbability (equations : Index → Equation Variable) (g : Variable → Bool) : ℚ :=
80
+ Finset.univ.expect (fun i : Index =>
81
+ (failedEquation (bobTriple g (equations i)) (equations i).rhs : ℚ))
82
+
83
+ theorem acceptance_probability_eq_expected_count (equations : Index → Equation Variable)
84
+ (alice : Index → Triple) (g : Variable → Bool) :
85
+ acceptanceProbability equations alice g =
86
+ Finset.univ.expect (fun i : Index =>
87
+ (acceptedSlots (alice i) (bobTriple g (equations i)) (equations i).rhs : ℚ) / 3) := by
88
+ unfold acceptanceProbability
89
+ rw [← Finset.univ_product_univ, Finset.expect_product]
90
+ exact Finset.expect_congr rfl (fun i _ => expect_slot_acceptance (equations i) (alice i) g)
91
+
92
+ theorem acceptance_probability_nonnegative (equations : Index → Equation Variable)
93
+ (alice : Index → Triple) (g : Variable → Bool) :
94
+ 0 ≤ acceptanceProbability equations alice g := by
95
+ apply Finset.expect_nonneg
96
+ intro q _
97
+ unfold slotAcceptance
98
+ split <;> norm_num
99
+
100
+ theorem acceptance_probability_le_one [Nonempty Index]
101
+ (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) :
102
+ acceptanceProbability equations alice g ≤ 1 := by
103
+ apply Finset.expect_le Finset.univ_nonempty
104
+ intro q _
105
+ unfold slotAcceptance
106
+ split <;> norm_num
107
+
108
+ theorem acceptance_plus_failure_third_le_one [Nonempty Index]
109
+ (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) :
110
+ acceptanceProbability equations alice g + failureProbability equations g / 3 ≤ 1 := by
111
+ rw [acceptance_probability_eq_expected_count]
112
+ unfold failureProbability
113
+ rw [Finset.expect_div, ← Finset.expect_add_distrib]
114
+ apply Finset.expect_le Finset.univ_nonempty
115
+ intro i _
116
+ have h : (acceptedSlots (alice i) (bobTriple g (equations i)) (equations i).rhs : ℚ) +
117
+ (failedEquation (bobTriple g (equations i)) (equations i).rhs : ℚ) ≤ 3 := by
118
+ exact_mod_cast local_count_bound (alice i) (bobTriple g (equations i)) (equations i).rhs
119
+ linarith
120
+
121
+ theorem deterministic_soundness [Nonempty Index]
122
+ (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool)
123
+ (gap : (1 : ℚ) / 64 ≤ failureProbability equations g) :
124
+ acceptanceProbability equations alice g ≤ (191 : ℚ) / 192 := by
125
+ have h := acceptance_plus_failure_third_le_one equations alice g
126
+ linarith
127
+
128
+ theorem failureCount_eq_countP (equations : I → Equation Variable)
129
+ (g : Variable → Bool) (xs : List I) :
130
+ failureCount equations g xs = xs.countP (fun i =>
131
+ decide (parity (bobTriple g (equations i)) ≠ (equations i).rhs)) := by
132
+ induction xs with
133
+ | nil => rfl
134
+ | cons i xs ih =>
135
+ simp only [failureCount, List.countP_cons, ih]
136
+ by_cases h : parity (bobTriple g (equations i)) = (equations i).rhs
137
+ · simp [failedEquation, h]
138
+ · simp [failedEquation, h, Nat.add_comm]
139
+
140
+ theorem failure_count_finRange_eq_count_ofFn {n : Nat}
141
+ (equations : Fin n → Equation Variable) (g : Variable → Bool) :
142
+ failureCount equations g (List.finRange n) =
143
+ (List.ofFn (fun i => decide
144
+ (parity (bobTriple g (equations i)) ≠ (equations i).rhs))).countP id := by
145
+ rw [failureCount_eq_countP]
146
+ have h := List.countP_map (l := List.finRange n)
147
+ (f := fun i => decide (parity (bobTriple g (equations i)) ≠ (equations i).rhs))
148
+ (p := id)
149
+ simpa only [List.finRange, List.map_ofFn, Function.comp_def, id_eq] using h.symm
150
+
151
+ theorem failure_probability_eq_count_finRange {n : Nat}
152
+ (equations : Fin n → Equation Variable) (g : Variable → Bool) :
153
+ failureProbability equations g =
154
+ (failureCount equations g (List.finRange n) : ℚ) / n := by
155
+ rw [failure_count_finRange_eq_count_ofFn]
156
+ rw [← expect_bool_indicator_eq_count_ofFn]
157
+ apply Finset.expect_congr rfl
158
+ intro i _
159
+ by_cases h : parity (bobTriple g (equations i)) = (equations i).rhs
160
+ · simp [failedEquation, h]
161
+ · simp [failedEquation, h]
162
+
163
+ theorem failure_gap_of_count_gap {n : Nat} (nonempty : 0 < n)
164
+ (equations : Fin n → Equation Variable) (g : Variable → Bool)
165
+ (gap : n ≤ 64 * failureCount equations g (List.finRange n)) :
166
+ (1 : ℚ) / 64 ≤ failureProbability equations g := by
167
+ rw [failure_probability_eq_count_finRange]
168
+ have hn : (0 : ℚ) < n := by exact_mod_cast nonempty
169
+ rw [le_div_iff₀ hn]
170
+ have hg : (n : ℚ) ≤ 64 * (failureCount equations g (List.finRange n) : ℚ) := by
171
+ exact_mod_cast gap
172
+ linarith
173
+
174
+ theorem soundness_from_count_gap {n : Nat} (nonempty : 0 < n)
175
+ (equations : Fin n → Equation Variable) (alice : Fin n → Triple) (g : Variable → Bool)
176
+ (gap : n ≤ 64 * failureCount equations g (List.finRange n)) :
177
+ acceptanceProbability equations alice g ≤ (191 : ℚ) / 192 := by
178
+ have : Nonempty (Fin n) := ⟨⟨0, nonempty⟩⟩
179
+ exact deterministic_soundness equations alice g
180
+ (failure_gap_of_count_gap nonempty equations g gap)
181
+
182
+ def randomizedAcceptance [Fintype Coin] (equations : Index → Equation Variable)
183
+ (weight : Coin → ℚ) (alice : Coin → Index → Triple)
184
+ (bob : Coin → Variable → Bool) : ℚ :=
185
+ ∑ c, weight c * acceptanceProbability equations (alice c) (bob c)
186
+
187
+ theorem randomized_soundness [Nonempty Index] [Fintype Coin]
188
+ (equations : Index → Equation Variable)
189
+ (gap : ∀ g : Variable → Bool, (1 : ℚ) / 64 ≤ failureProbability equations g)
190
+ (weight : Coin → ℚ) (weight_nonnegative : ∀ c, 0 ≤ weight c)
191
+ (weight_sum : ∑ c, weight c = 1)
192
+ (alice : Coin → Index → Triple) (bob : Coin → Variable → Bool) :
193
+ randomizedAcceptance equations weight alice bob ≤ (191 : ℚ) / 192 := by
194
+ calc
195
+ randomizedAcceptance equations weight alice bob ≤
196
+ ∑ c, weight c * ((191 : ℚ) / 192) := by
197
+ apply Finset.sum_le_sum
198
+ intro c _
199
+ exact mul_le_mul_of_nonneg_left
200
+ (deterministic_soundness equations (alice c) (bob c) (gap (bob c)))
201
+ (weight_nonnegative c)
202
+ _ = (191 : ℚ) / 192 := by rw [← Finset.sum_mul, weight_sum, one_mul]
203
+
204
+ instance tripleFintype : Fintype Triple :=
205
+ Fintype.ofEquiv (Bool × Bool × Bool)
206
+ { toFun := fun t => ⟨t.1, t.2.1, t.2.2⟩
207
+ invFun := fun t => (t.first, t.second, t.third)
208
+ left_inv := fun _ => rfl
209
+ right_inv := fun _ => rfl }
210
+
211
+ instance tripleInhabited : Inhabited Triple := ⟨⟨false, false, false⟩⟩
212
+
213
+ noncomputable def deterministicValue [Fintype Variable]
214
+ (equations : Index → Equation Variable) : ℚ := by
215
+ classical
216
+ exact Finset.univ.sup' Finset.univ_nonempty
217
+ (fun s : (Index → Triple) × (Variable → Bool) =>
218
+ acceptanceProbability equations s.1 s.2)
219
+
220
+ theorem acceptance_le_value [Fintype Variable]
221
+ (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) :
222
+ acceptanceProbability equations alice g ≤ deterministicValue equations := by
223
+ classical
224
+ exact Finset.le_sup'
225
+ (fun s : (Index → Triple) × (Variable → Bool) =>
226
+ acceptanceProbability equations s.1 s.2) (Finset.mem_univ (alice, g))
227
+
228
+ theorem value_attained [Fintype Variable] (equations : Index → Equation Variable) :
229
+ ∃ (alice : Index → Triple) (g : Variable → Bool),
230
+ acceptanceProbability equations alice g = deterministicValue equations := by
231
+ classical
232
+ obtain ⟨s, _, hs⟩ := Finset.exists_mem_eq_sup' Finset.univ_nonempty
233
+ (fun s : (Index → Triple) × (Variable → Bool) =>
234
+ acceptanceProbability equations s.1 s.2)
235
+ exact ⟨s.1, s.2, hs.symm⟩
236
+
237
+ theorem value_soundness [Nonempty Index] [Fintype Variable]
238
+ (equations : Index → Equation Variable)
239
+ (gap : ∀ g : Variable → Bool, (1 : ℚ) / 64 ≤ failureProbability equations g) :
240
+ deterministicValue equations ≤ (191 : ℚ) / 192 := by
241
+ classical
242
+ apply Finset.sup'_le
243
+ intro s _
244
+ exact deterministic_soundness equations s.1 s.2 (gap s.2)
245
+
246
+ theorem randomized_acceptance_le_value [Fintype Variable] [Fintype Coin]
247
+ (equations : Index → Equation Variable)
248
+ (weight : Coin → ℚ) (weight_nonnegative : ∀ c, 0 ≤ weight c)
249
+ (weight_sum : ∑ c, weight c = 1)
250
+ (alice : Coin → Index → Triple) (bob : Coin → Variable → Bool) :
251
+ randomizedAcceptance equations weight alice bob ≤ deterministicValue equations := by
252
+ calc
253
+ randomizedAcceptance equations weight alice bob ≤
254
+ ∑ c, weight c * deterministicValue equations := by
255
+ apply Finset.sum_le_sum
256
+ intro c _
257
+ exact mul_le_mul_of_nonneg_left
258
+ (acceptance_le_value equations (alice c) (bob c)) (weight_nonnegative c)
259
+ _ = deterministicValue equations := by rw [← Finset.sum_mul, weight_sum, one_mul]
260
+
261
+ theorem randomized_value_attained [Fintype Variable] [Fintype Coin]
262
+ (equations : Index → Equation Variable) (weight : Coin → ℚ)
263
+ (weight_sum : ∑ c, weight c = 1) :
264
+ ∃ (alice : Coin → Index → Triple) (bob : Coin → Variable → Bool),
265
+ randomizedAcceptance equations weight alice bob = deterministicValue equations := by
266
+ obtain ⟨alice, bob, h⟩ := value_attained equations
267
+ refine ⟨fun _ => alice, fun _ => bob, ?_⟩
268
+ simp only [randomizedAcceptance, h, ← Finset.sum_mul, weight_sum, one_mul]
269
+
270
+ theorem cloned_failure_probability_gap (s : ActualSource.Source)
271
+ (source_gap : ∀ A : Fin s.«variables» → Bool,
272
+ s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !CloneGap.satisfied e A))
273
+ (g : FiniteSource.Name s → Bool) :
274
+ (1 : ℚ) / 64 ≤ failureProbability (FiniteSource.incidenceEquation s) g := by
275
+ apply failure_gap_of_count_gap (FiniteSource.clonedSource_nonempty s)
276
+ simpa only [FiniteSource.occurrences, List.length_finRange] using
277
+ FiniteSource.incidence_failure_gap s source_gap g
278
+
279
+ theorem cloned_value_soundness (s : ActualSource.Source)
280
+ (source_gap : ∀ A : Fin s.«variables» → Bool,
281
+ s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !CloneGap.satisfied e A)) :
282
+ deterministicValue (FiniteSource.incidenceEquation s) ≤ (191 : ℚ) / 192 := by
283
+ exact value_soundness _ (cloned_failure_probability_gap s source_gap)
284
+
285
+ theorem cloned_randomized_soundness [Fintype Coin] (s : ActualSource.Source)
286
+ (source_gap : ∀ A : Fin s.«variables» → Bool,
287
+ s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !CloneGap.satisfied e A))
288
+ (weight : Coin → ℚ) (weight_nonnegative : ∀ c, 0 ≤ weight c)
289
+ (weight_sum : ∑ c, weight c = 1)
290
+ (alice : Coin → FiniteSource.Occurrence s → Triple)
291
+ (bob : Coin → FiniteSource.Name s → Bool) :
292
+ randomizedAcceptance (FiniteSource.incidenceEquation s) weight alice bob ≤
293
+ (191 : ℚ) / 192 := by
294
+ exact randomized_soundness _ (cloned_failure_probability_gap s source_gap)
295
+ weight weight_nonnegative weight_sum alice bob
296
+
297
+ namespace FoundationBridge
298
+
299
+ variable {Variable Index I : Type} [Fintype Index]
300
+
301
+ open MinUncutGames.Foundations.Games
302
+ open MinUncutGames.Soundness.IncidenceExtraction (Incidence)
303
+
304
+ noncomputable def uniformDistribution (Ω : Type*) [Fintype Ω] [Nonempty Ω] :
305
+ FiniteDistribution Ω where
306
+ weight _ := (Fintype.card Ω : ℝ)⁻¹
307
+ nonnegative _ := inv_nonneg.mpr (Nat.cast_nonneg _)
308
+ normalized := by
309
+ have h : (Fintype.card Ω : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero
310
+ simp [h]
311
+
312
+ theorem uniform_probability_eq_rat_expect {Ω : Type*} [Fintype Ω] [Nonempty Ω]
313
+ (event : Ω → Bool) :
314
+ (uniformDistribution Ω).probability event =
315
+ ((Finset.univ.expect (fun x => if event x then (1 : ℚ) else 0) : ℚ) : ℝ) := by
316
+ unfold FiniteDistribution.probability uniformDistribution
317
+ rw [Fintype.expect_eq_sum_div_card]
318
+ push_cast
319
+ rw [div_eq_mul_inv, Finset.sum_mul]
320
+ apply Finset.sum_congr rfl
321
+ intro x _
322
+ cases event x <;> simp
323
+
324
+ def functionalTriple (a : Fin 3 → Bool) : Triple := ⟨a 0, a 1, a 2⟩
325
+
326
+ theorem functionalTriple_bitAt (a : Fin 3 → Bool) (i : Fin 3) :
327
+ bitAt (functionalTriple a) (slotOfFin i) = a i := by
328
+ fin_cases i <;> simp [functionalTriple, slotOfFin, bitAt]
329
+
330
+ def extractionIncidence (equations : I → Equation Variable) :
331
+ MinUncutGames.Soundness.IncidenceExtraction.Incidence I Variable where
332
+ name o i := nameAt (equations o) (slotOfFin i)
333
+ rhs o := (equations o).rhs
334
+
335
+ def DistinctNames (equations : I → Equation Variable) : Prop :=
336
+ ∀ o, (equations o).first ≠ (equations o).second ∧
337
+ (equations o).first ≠ (equations o).third ∧
338
+ (equations o).second ≠ (equations o).third
339
+
340
+ theorem extraction_names_injective (equations : I → Equation Variable)
341
+ (distinct : DistinctNames equations) :
342
+ ∀ o i j, (extractionIncidence equations).name o i =
343
+ (extractionIncidence equations).name o j → i = j := by
344
+ intro o i j
345
+ obtain ⟨h12, h13, h23⟩ := distinct o
346
+ have h21 := Ne.symm h12
347
+ have h31 := Ne.symm h13
348
+ have h32 := Ne.symm h23
349
+ fin_cases i <;> fin_cases j <;>
350
+ simp_all [extractionIncidence, slotOfFin, nameAt]
351
+
352
+ noncomputable def foundationGame [Nonempty Index] [Fintype Variable]
353
+ (equations : Index → Equation Variable) : Game Index Variable (Fin 3 → Bool) Bool := by
354
+ classical
355
+ exact
356
+ { questions := (uniformDistribution (Index × Fin 3)).pushforward
357
+ (fun q => (q.1, (extractionIncidence equations).name q.1 q.2))
358
+ accepts := fun o name a b => decide
359
+ ((extractionIncidence equations).namedAccepts o name a b) }
360
+
361
+ theorem foundation_success_eq_rat_acceptance [Nonempty Index] [Fintype Variable]
362
+ (equations : Index → Equation Variable) (distinct : DistinctNames equations)
363
+ (alice : Index → Fin 3 → Bool) (bob : Variable → Bool) :
364
+ (foundationGame equations).success (alice, bob) =
365
+ (acceptanceProbability equations (fun o => functionalTriple (alice o)) bob : ℝ) := by
366
+ classical
367
+ have hRat : Finset.univ.expect (fun q : Index × Fin 3 =>
368
+ if (extractionIncidence equations).namedAccepts q.1
369
+ ((extractionIncidence equations).name q.1 q.2) (alice q.1)
370
+ (bob ((extractionIncidence equations).name q.1 q.2)) then (1 : ℚ) else 0) =
371
+ acceptanceProbability equations (fun o => functionalTriple (alice o)) bob := by
372
+ apply Finset.expect_congr rfl
373
+ intro q _
374
+ have heq : (extractionIncidence equations).namedAccepts q.1
375
+ ((extractionIncidence equations).name q.1 q.2) (alice q.1)
376
+ (bob ((extractionIncidence equations).name q.1 q.2)) ↔
377
+ slotPredicate (equations q.1) (functionalTriple (alice q.1)) bob q.2 := by
378
+ rw [MinUncutGames.Soundness.IncidenceExtraction.Incidence.namedAccepts_iff_accepts _
379
+ (extraction_names_injective equations distinct)]
380
+ simp only [MinUncutGames.Soundness.IncidenceExtraction.Incidence.accepts,
381
+ slotPredicate, functionalTriple_bitAt]
382
+ rfl
383
+ by_cases h : slotPredicate (equations q.1) (functionalTriple (alice q.1)) bob q.2
384
+ · simp only [slotAcceptance, ite_eq_left h, ite_eq_left (heq.mpr h)]
385
+ · have hn := fun hn => h (heq.mp hn)
386
+ simp only [slotAcceptance, ite_eq_right h, ite_eq_right hn]
387
+ unfold Game.success foundationGame
388
+ rw [FiniteDistribution.probability_pushforward, uniform_probability_eq_rat_expect]
389
+ simpa only [Game.wins, decide_eq_true_eq] using congrArg (fun x : ℚ => (x : ℝ)) hRat
390
+
391
+ theorem foundation_value_soundness [Nonempty Index] [Fintype Variable]
392
+ (equations : Index → Equation Variable) (distinct : DistinctNames equations)
393
+ (gap : ∀ g : Variable → Bool, (1 : ℚ) / 64 ≤ failureProbability equations g) :
394
+ (foundationGame equations).value ≤ (191 : ℝ) / 192 := by
395
+ apply (Game.value_le_iff _ _).2
396
+ intro strategy
397
+ rw [foundation_success_eq_rat_acceptance equations distinct]
398
+ have h := (Rat.cast_le (K := ℝ)).mpr (deterministic_soundness equations
399
+ (fun o => functionalTriple (strategy.1 o)) strategy.2 (gap strategy.2))
400
+ norm_num at h ⊢
401
+ exact h
402
+
403
+ theorem foundation_value_le_one_sub_gap_third [Nonempty Index] [Fintype Variable]
404
+ (equations : Index → Equation Variable) (distinct : DistinctNames equations)
405
+ (epsilon : ℝ)
406
+ (gap : ∀ g : Variable → Bool, epsilon ≤ (failureProbability equations g : ℝ)) :
407
+ (foundationGame equations).value ≤ 1 - epsilon / 3 := by
408
+ apply (Game.value_le_iff _ _).2
409
+ intro strategy
410
+ rw [foundation_success_eq_rat_acceptance equations distinct]
411
+ have h := (Rat.cast_le (K := ℝ)).mpr
412
+ (acceptance_plus_failure_third_le_one equations
413
+ (fun o => functionalTriple (strategy.1 o)) strategy.2)
414
+ push_cast at h
415
+ linarith [gap strategy.2]
416
+
417
+ def sourceEquation (s : ActualSource.Source) : Fin s.occurrences → Equation (Fin s.«variables») :=
418
+ fun i => SourceIncidence.toIncidence (s.equation i)
419
+
420
+ noncomputable def sourceGame (s : ActualSource.Source) :
421
+ Game (Fin s.occurrences) (Fin s.«variables») (Fin 3 → Bool) Bool :=
422
+ foundationGame (sourceEquation s)
423
+
424
+ theorem source_failure_probability (s : ActualSource.Source) (g : Fin s.«variables» → Bool) :
425
+ failureProbability (sourceEquation s) g = s.failure g := by
426
+ unfold failureProbability ActualSource.Source.failure
427
+ apply Finset.expect_congr rfl
428
+ intro i _
429
+ simp only [sourceEquation, SourceIncidence.failedEquation_eq, ActualSource.Source.satisfied]
430
+ by_cases h : CloneGap.satisfied (s.equation i) g = true <;> simp [h]
431
+
432
+ theorem source_value_le_one_sub_gap_third (s : ActualSource.Source)
433
+ (distinct : s.DistinctNames) (epsilon : ℝ)
434
+ (gap : ∀ g : Fin s.«variables» → Bool, epsilon ≤ (s.failure g : ℝ)) :
435
+ (sourceGame s).value ≤ 1 - epsilon / 3 := by
436
+ apply foundation_value_le_one_sub_gap_third (sourceEquation s) distinct epsilon
437
+ intro g
438
+ rw [source_failure_probability]
439
+ exact gap g
440
+
441
+ theorem cloned_foundation_value_soundness (s : ActualSource.Source)
442
+ (source_gap : ∀ A : Fin s.«variables» → Bool,
443
+ s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !CloneGap.satisfied e A)) :
444
+ (foundationGame (FiniteSource.incidenceEquation s)).value ≤ (191 : ℝ) / 192 := by
445
+ apply foundation_value_soundness _ _ (cloned_failure_probability_gap s source_gap)
446
+ intro o
447
+ exact FiniteSource.names_distinct s o
448
+
449
+ end FoundationBridge
450
+
451
+ end MinUncutGames.Reduction.IncidenceProbability
452
+
453
+ end
454
+ section
455
+ namespace MinUncutGames.Reduction.SourceProbability
456
+
457
+ open ActualSource
458
+
459
+ theorem Source_failure_eq_count (S : Source) (A : Fin S.«variables» → Bool) :
460
+ S.failure A =
461
+ (S.sourceList.countP (fun e => !CloneGap.satisfied e A) : ℚ) / S.occurrences := by
462
+ have hp := IncidenceProbability.expect_bool_indicator_eq_count_ofFn
463
+ (fun i : Fin S.occurrences => !S.satisfied A i)
464
+ have he : Finset.univ.expect
465
+ (fun i : Fin S.occurrences => if !S.satisfied A i then (1 : ℚ) else 0) =
466
+ S.failure A := by
467
+ unfold Source.failure
468
+ congr 1
469
+ funext i
470
+ cases S.satisfied A i <;> rfl
471
+ rw [he] at hp
472
+ rw [hp]
473
+ congr 2
474
+ have hmap : List.ofFn (fun i : Fin S.occurrences => !S.satisfied A i) =
475
+ S.sourceList.map (fun e => !CloneGap.satisfied e A) := by
476
+ simp only [Source.sourceList, List.map_ofFn, Source.satisfied, Function.comp_def]
477
+ rw [hmap, List.countP_map]
478
+ rfl
479
+
480
+ theorem ofList_failure {n : Nat} (es : List (CloneGap.Equation (Fin n)))
481
+ (hne : es ≠ []) (A : Fin n → Bool) :
482
+ (Source.ofList es hne).failure A =
483
+ (es.countP (fun e => !CloneGap.satisfied e A) : ℚ) / es.length := by
484
+ have h := Source_failure_eq_count (Source.ofList es hne) A
485
+ simpa [Source.sourceList, Source.ofList] using h
486
+
487
+ theorem count_complement {α : Type*} (es : List α) (p : α → Bool) :
488
+ es.countP (fun e => !p e) + es.countP p = es.length := by
489
+ induction es with
490
+ | nil => simp
491
+ | cons e es ih =>
492
+ cases hp : p e <;> simp [hp] at * <;> omega
493
+
494
+ theorem failure_add_satisfaction (S : Source) (A : Fin S.«variables» → Bool) :
495
+ S.failure A +
496
+ (S.sourceList.countP (fun e => CloneGap.satisfied e A) : ℚ) / S.occurrences = 1 := by
497
+ rw [Source_failure_eq_count, ← add_div]
498
+ have h := count_complement S.sourceList (fun e => CloneGap.satisfied e A)
499
+ have hc : ((S.sourceList.countP (fun e => !CloneGap.satisfied e A) : ℚ) +
500
+ (S.sourceList.countP (fun e => CloneGap.satisfied e A) : ℚ)) = S.occurrences := by
501
+ exact_mod_cast (h.trans S.sourceList_length)
502
+ rw [hc, div_self]
503
+ exact_mod_cast Nat.ne_of_gt S.nonempty
504
+
505
+ theorem quarter_gap_iff (S : Source) (A : Fin S.«variables» → Bool) :
506
+ (1 / 4 : ℚ) ≤ S.failure A ↔
507
+ S.sourceList.length ≤ 4 * S.sourceList.countP (fun e => !CloneGap.satisfied e A) := by
508
+ rw [Source_failure_eq_count]
509
+ have hn : (0 : ℚ) < S.occurrences := by exact_mod_cast S.nonempty
510
+ rw [le_div_iff₀ hn]
511
+ constructor
512
+ · intro h
513
+ have h' : (S.occurrences : ℚ) ≤ 4 *
514
+ (S.sourceList.countP (fun e => !CloneGap.satisfied e A) : ℚ) := by linarith
515
+ rw [S.sourceList_length]
516
+ exact_mod_cast h'
517
+ · intro h
518
+ rw [S.sourceList_length] at h
519
+ have h' : (S.occurrences : ℚ) ≤ 4 *
520
+ (S.sourceList.countP (fun e => !CloneGap.satisfied e A) : ℚ) := by exact_mod_cast h
521
+ linarith
522
+
523
+ end MinUncutGames.Reduction.SourceProbability
524
+
525
+ end
526
+
527
+ end OAI
lean/OAI/Computability/MinUncut/Games/JointCoefficient.lean ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.PCP.Parity
3
+
4
+ namespace OAI
5
+
6
+ noncomputable section
7
+ open scoped BigOperators
8
+ open MeasureTheory ProbabilityTheory Filter
9
+ open scoped Topology NNReal
10
+ open scoped BigOperators
11
+ open MeasureTheory ProbabilityTheory Polynomial Filter
12
+ open scoped BigOperators Topology
13
+ open MeasureTheory ProbabilityTheory WithLp
14
+ open scoped BigOperators RealInnerProductSpace
15
+ namespace MinUncut.Inner
16
+ open MeasureTheory ProbabilityTheory
17
+ open scoped BigOperators
18
+ variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]
19
+ variable {m n : ℕ}
20
+
21
+ def jointCoefficient (f : FoldedProof A) (σ η : ℝ) (x : Point m n)
22
+ (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ) : ℝ :=
23
+ BinaryFourier.coefficient
24
+ (fun B => GaussianHermite.coeff (fun c => gradient f B σ η c x) I) α
25
+
26
+ def constantArray (k : Row m n → F₂) : FaceArray A m n := fun r => AffineMap.const F₂ A (k r)
27
+
28
+ omit [Fintype A] in
29
+ lemma constantArray_add (B : FaceArray A m n) (k : Row m n → F₂) :
30
+ constantArray k+B = addConstantArray B k := by
31
+ funext r; exact add_comm _ _
32
+
33
+ lemma hermite_gradient_constantArray (f : FoldedProof A) (B : FaceArray A m n)
34
+ (k : Row m n → F₂) {σ : ℝ} (hσ : σ ≠ 0) (η : ℝ) (x : Point m n) (I : Point m n → ℕ) :
35
+ GaussianHermite.coeff (fun c => gradient f (constantArray k+B) σ η c x) I =
36
+ BinaryFourier.sign ((rowCode k).val x + GaussianHermite.parity (rowCode k).val I) *
37
+ GaussianHermite.coeff (fun c => gradient f B σ η c x) I := by
38
+ simp only [constantArray_add, gradient_addConstantArray f B k hσ,
39
+ GaussianHermite.coeff_const_mul, BinaryFourier.sign_add, mul_assoc]
40
+ rw [GaussianHermite.coeff_diagonal (rowCode k).val (fun c => gradient f B σ η c x) I]
41
+
42
+ lemma sign_injective : Function.Injective BinaryFourier.sign := by
43
+ intro a b hab
44
+ have h : ∀ x : F₂, x=0 ∨ x=1 := by decide
45
+ rcases h a with rfl | rfl
46
+ · rcases h b with rfl | rfl
47
+ · rfl
48
+ · norm_num at hab
49
+ · rcases h b with rfl | rfl
50
+ · norm_num at hab
51
+ · rfl
52
+
53
+ theorem joint_row_gauge (f : FoldedProof A) {σ : ℝ} (hσ : σ ≠ 0) (η : ℝ)
54
+ (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ)
55
+ (hne : jointCoefficient f σ η x α I ≠ 0) (k : Row m n → F₂) :
56
+ α (constantArray k) = (rowCode k).val x + GaussianHermite.parity (rowCode k).val I := by
57
+ have ht := BinaryFourier.coefficient_translate
58
+ (fun B : FaceArray A m n => GaussianHermite.coeff (fun c => gradient f B σ η c x) I)
59
+ α (constantArray k)
60
+ simp only [hermite_gradient_constantArray f _ k hσ, BinaryFourier.coefficient,
61
+ mul_assoc, ← Finset.mul_expect] at ht
62
+ apply sign_injective
63
+ change _ * jointCoefficient f σ η x α I = _ * jointCoefficient f σ η x α I at ht
64
+ exact mul_right_cancel₀ hne ht.symm
65
+
66
+ theorem joint_cylinder_gauge (f : FoldedProof A) (σ η : ℝ)
67
+ (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ)
68
+ (hne : jointCoefficient f σ η x α I ≠ 0)
69
+ (i j : Fin m) (hij : i ≠ j) (q : Point m n) (a : Forms A) :
70
+ α (cylinderArray i j q a) = 0 := by
71
+ have ht := BinaryFourier.coefficient_translate
72
+ (fun B : FaceArray A m n => GaussianHermite.coeff (fun c => gradient f B σ η c x) I)
73
+ α (cylinderArray i j q a)
74
+ have hg (B : FaceArray A m n) : gradient f (cylinderArray i j q a+B) σ η =
75
+ gradient f B σ η := by rw [add_comm, gradient_cylinder f B i j hij]
76
+ simp only [hg] at ht
77
+ by_contra hn
78
+ have hs : BinaryFourier.character α (cylinderArray i j q a) = -1 := by
79
+ simp [BinaryFourier.character, BinaryFourier.sign, hn]
80
+ rw [hs] at ht
81
+ exact hne (by change jointCoefficient f σ η x α I = -1*jointCoefficient f σ η x α I at ht; linarith)
82
+ end MinUncut.Inner
83
+
84
+ end
85
+
86
+ end OAI
lean/OAI/Computability/MinUncut/Games/JointHintBound.lean ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.JointHintSampling
3
+ import OAI.Computability.MinUncut.Estimates.PatchDensity
4
+
5
+ namespace OAI
6
+
7
+ noncomputable section
8
+ open scoped BigOperators
9
+ namespace MinUncut.Outer
10
+ open MinUncut.Inner OuterSmoothness
11
+ attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype
12
+ variable {Name I : Type*} [Fintype I]
13
+
14
+ lemma raw_background_expect (U : I → Equation Name) {d : ℕ} (H : Finset I)
15
+ (f : (Fin d → Forms (FirstAlphabet U)) → ℝ) :
16
+ (𝔼 pos : I → Fin 3,
17
+ 𝔼 L : Fin d → Forms (SecondAlphabet (secondQuestion U (hiddenSet H) pos)),
18
+ f (fun k => formPullback (projection U (hiddenSet H) pos) (L k))) =
19
+ (𝔼 z : (Fin d → F₂) × (I → JointForms.Raw d),
20
+ f (firstHints U (hiddenSet H) (rawPositions z.2) (rawCoefficients z.1 z.2))) := by
21
+ classical
22
+ have hpos (pos : I → Fin 3) :
23
+ (𝔼 L : Fin d → Forms (SecondAlphabet (secondQuestion U (hiddenSet H) pos)),
24
+ f (fun k => formPullback (projection U (hiddenSet H) pos) (L k))) =
25
+ (𝔼 c : HintCoefficients I d, f (firstHints U (hiddenSet H) pos c)) :=
26
+ (uniform_hintTupleGenerator _ d (fun L =>
27
+ f (fun k => formPullback (projection U (hiddenSet H) pos) (L k)))).symm
28
+ simp_rw [hpos]
29
+ rw [← expect_pair (fun z : (I → Fin 3) × HintCoefficients I d =>
30
+ f (firstHints U (hiddenSet H) z.1 z.2))]
31
+ exact Fintype.expect_equiv (hintRawEquiv (I := I) d) _ _ (fun z => rfl)
32
+
33
+ lemma actual_joint_law (U : I → Equation Name) {d k : ℕ} (hk : k≤Fintype.card I)
34
+ (f : (Fin d → Forms (FirstAlphabet U)) → ℝ) :
35
+ let : Nonempty (FixedSets I k) := fixedSets_nonempty hk
36
+ (𝔼 H : FixedSets I k,𝔼 pos : I → Fin 3,
37
+ 𝔼 L : Fin d → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)),
38
+ f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L j))) =
39
+ (𝔼 sample : (Fin d → F₂) × (FixedSets I k × (I → JointForms.Raw d)),
40
+ f (tupleCoordinateGenerator U d
41
+ (JointForms.affineOutput (fun i => directionEmbedding (U i))
42
+ (fun i => (origin (U i)).val) sample))) := by
43
+ classical
44
+ let : Nonempty (FixedSets I k) := fixedSets_nonempty hk
45
+ simp_rw [raw_background_expect]
46
+ rw [expect_pair]
47
+ simp_rw [expect_pair]
48
+ rw [Finset.expect_comm]
49
+ apply Finset.expect_congr rfl
50
+ intro κ _
51
+ apply Finset.expect_congr rfl
52
+ intro H _
53
+ apply Finset.expect_congr rfl
54
+ intro w _
55
+ exact congrArg f (raw_joint_identity U H κ w)
56
+
57
+ theorem actual_joint_smoothness [Nonempty I] (U : I → Equation Name) {d k : ℕ}
58
+ (hk : k≤Fintype.card I) (f : (Fin d → Forms (FirstAlphabet U)) → ℝ)
59
+ {M : ℝ} (hM : 0≤M) (hf : ∀ L, |f L|≤M) :
60
+ let : Nonempty (FixedSets I k) := fixedSets_nonempty hk
61
+ |(𝔼 H : FixedSets I k,𝔼 pos : I → Fin 3,
62
+ 𝔼 L : Fin d → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)),
63
+ f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L j))) -
64
+ (𝔼 L : Fin d → Forms (FirstAlphabet U), f L)| ≤
65
+ Real.sqrt (((2 : ℝ)^(4*d*k)-1)*(k : ℝ)^2/Fintype.card I)*M := by
66
+ classical
67
+ let : Nonempty (FixedSets I k) := fixedSets_nonempty hk
68
+ rw [actual_joint_law U hk]
69
+ let output := JointForms.affineOutput (fun i => directionEmbedding (U i))
70
+ (fun i => (origin (U i)).val) (d := d) (k := k)
71
+ have h := Density.expect_difference (Density.ofMap output)
72
+ (fun z => f (tupleCoordinateGenerator U d z)) hM (fun z => hf _)
73
+ rw [Density.expect_ofMap,uniform_tupleCoordinateGenerator] at h
74
+ have htv := JointForms.joint_smoothness hk (fun i => alphabet_dimension_le (U i))
75
+ (fun i => directionEmbedding (U i)) (fun i => directionEmbedding_injective (U i))
76
+ (fun i => (origin (U i)).val) (d := d)
77
+ refine h.trans ?_
78
+ calc
79
+ _ ≤ 2 * (Real.sqrt (((2 : ℝ)^(4*d*k)-1)*(k : ℝ)^2/Fintype.card I)/2)*M := by
80
+ gcongr
81
+ convert htv using 1
82
+ exact Density.tv_ofMap_instances _ _ _ _ _ _ _ _ output
83
+ _ = _ := by ring
84
+
85
+ end MinUncut.Outer
86
+
87
+ namespace MinUncut.Outer
88
+ open MinUncut.Inner OuterSmoothness
89
+ attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype
90
+
91
+ lemma expect_reindex {J K A : Type*} [Fintype J] [Fintype K] [Fintype A] [DecidableEq J] [DecidableEq K]
92
+ (e : J ≃ K) (f : (J → A) → ℝ) :
93
+ (𝔼 L : K → A, f (fun j => L (e j))) = 𝔼 L : J → A, f L := by
94
+ exact Fintype.expect_equiv (Equiv.arrowCongr e.symm (Equiv.refl A)) _ _ (fun _ => rfl)
95
+
96
+ variable {Name I J : Type*} [Fintype I] [Fintype J] [DecidableEq J]
97
+
98
+ lemma pulled_background_reindex {K : Type*} [Fintype K] [DecidableEq K]
99
+ (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3)
100
+ (e : J ≃ K) (f : (J → Forms (FirstAlphabet U)) → ℝ) :
101
+ (𝔼 L : K → Forms (SecondAlphabet (secondQuestion U hidden pos)),
102
+ f (fun j => formPullback (projection U hidden pos) (L (e j)))) =
103
+ 𝔼 L : J → Forms (SecondAlphabet (secondQuestion U hidden pos)),
104
+ f (fun j => formPullback (projection U hidden pos) (L j)) :=
105
+ expect_reindex e (fun L => f (fun j => formPullback (projection U hidden pos) (L j)))
106
+
107
+ lemma actual_background_reindex {K : Type*} [Fintype K] [DecidableEq K]
108
+ (U : I → Equation Name) (k : ℕ) (e : J ≃ K)
109
+ (f : (J → Forms (FirstAlphabet U)) → ℝ) :
110
+ (𝔼 H : FixedSets I k, 𝔼 pos : I → Fin 3,
111
+ 𝔼 L : K → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)),
112
+ f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L (e j)))) =
113
+ 𝔼 H : FixedSets I k, 𝔼 pos : I → Fin 3,
114
+ 𝔼 L : J → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)),
115
+ f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L j)) := by
116
+ apply Finset.expect_congr rfl
117
+ intro H _
118
+ exact Finset.expect_congr rfl (fun pos _ => pulled_background_reindex U _ pos e f)
119
+
120
+ theorem actual_joint_smoothness_index [Nonempty I] (U : I → Equation Name) {k : ℕ}
121
+ (hk : k≤Fintype.card I) (f : (J → Forms (FirstAlphabet U)) → ℝ)
122
+ {M : ℝ} (hM : 0≤M) (hf : ∀ L, |f L|≤M) :
123
+ let : Nonempty (FixedSets I k) := fixedSets_nonempty hk
124
+ |(𝔼 H : FixedSets I k,𝔼 pos : I → Fin 3,
125
+ 𝔼 L : J → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)),
126
+ f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L j))) -
127
+ (𝔼 L : J → Forms (FirstAlphabet U), f L)| ≤
128
+ Real.sqrt (((2 : ℝ)^(4*Fintype.card J*k)-1)*(k : ℝ)^2/Fintype.card I)*M := by
129
+ let : Nonempty (FixedSets I k) := fixedSets_nonempty hk
130
+ let e := Fintype.equivFin J
131
+ have h := actual_joint_smoothness (d := Fintype.card J) U hk (fun L => f (fun j => L (e j))) hM
132
+ (fun L => hf _)
133
+ dsimp only at h
134
+ rw [actual_background_reindex U k e f,expect_reindex e f] at h
135
+ exact h
136
+
137
+ end MinUncut.Outer
138
+
139
+ end
140
+
141
+ end OAI
lean/OAI/Computability/MinUncut/Games/JointHintSampling.lean ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.ListDecoding
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ noncomputable section
8
+ open scoped BigOperators
9
+ namespace MinUncut.Outer
10
+ open MinUncut.Inner OuterSmoothness
11
+ attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype
12
+ variable {Name I : Type*} [Fintype I]
13
+
14
+ def hiddenSet (H : Finset I) : I → Bool := fun i => decide (i ∈ H)
15
+ def rawPositions {d : ℕ} (w : I → JointForms.Raw d) : I → Fin 3 := fun i => (w i).1.1
16
+ def rawCoefficients {d : ℕ} (κ : Fin d → F₂) (w : I → JointForms.Raw d) :
17
+ HintCoefficients I d := fun k => (κ k,(fun i => (w i).1.2 k,fun i => (w i).2 k))
18
+
19
+ def hintRawEquiv (d : ℕ) :
20
+ ((I → Fin 3) × HintCoefficients I d) ≃ ((Fin d → F₂) × (I → JointForms.Raw d)) where
21
+ toFun z := (fun k => (z.2 k).1,fun i => ((z.1 i,fun k => (z.2 k).2.1 i),
22
+ fun k => (z.2 k).2.2 i))
23
+ invFun z := (rawPositions z.2,rawCoefficients z.1 z.2)
24
+ left_inv _ := rfl
25
+ right_inv _ := rfl
26
+
27
+ lemma origin_coordinate_decomposition (E : Equation Name) (a : alphabet E) :
28
+ a.val=directionEmbedding E ((alphabetCoordinates E).symm a)+(origin E).val := by
29
+ exact congrArg Subtype.val ((alphabetCoordinates E).apply_symm_apply a) |>.symm
30
+
31
+ omit [Fintype I] in
32
+ lemma raw_slot_expansion (U : I → Equation Name) {d : ℕ} (H : Finset I)
33
+ (w : I → JointForms.Raw d) (a : FirstAlphabet U) (i : I) (k : Fin d) :
34
+ (if i ∈ H then (w i).1.2 k*(a i).val (w i).1.1 else (w i).2 k (a i).val) =
35
+ (JointForms.output (fun i => directionEmbedding (U i)) H w i k)
36
+ ((alphabetCoordinates (U i)).symm (a i)) +
37
+ (if i ∈ H then (w i).1.2 k*(origin (U i)).val (w i).1.1
38
+ else (w i).2 k (origin (U i)).val) := by
39
+ classical
40
+ by_cases hi : i ∈ H
41
+ · simp only [hi,↓reduceIte,JointForms.output,JointForms.hiddenPull]
42
+ change (w i).1.2 k*(a i).val (w i).1.1 =
43
+ (w i).1.2 k*(directionEmbedding (U i) ((alphabetCoordinates (U i)).symm (a i))) (w i).1.1+_
44
+ rw [origin_coordinate_decomposition (U i) (a i)]
45
+ simp only [Pi.add_apply,mul_add]
46
+ · simp only [hi,↓reduceIte,JointForms.output,JointForms.fullPull,
47
+ LinearMap.pi_apply,LinearMap.comp_apply,LinearMap.proj_apply,LinearMap.dualMap_apply]
48
+ rw [origin_coordinate_decomposition (U i) (a i),map_add]
49
+
50
+ lemma raw_joint_identity (U : I → Equation Name) {d k : ℕ} (H : FixedSets I k)
51
+ (κ : Fin d → F₂) (w : I → JointForms.Raw d) :
52
+ firstHints U (hiddenSet H.val) (rawPositions w) (rawCoefficients κ w) =
53
+ tupleCoordinateGenerator U d
54
+ (JointForms.affineOutput (fun i => directionEmbedding (U i))
55
+ (fun i => (origin (U i)).val) (κ,H,w)) := by
56
+ classical
57
+ funext l
58
+ apply AffineMap.ext
59
+ intro a
60
+ change formPullback (projection U (hiddenSet H.val) (rawPositions w))
61
+ (directHint _ (κ l) (fun i => (w i).1.2 l) (fun i => (w i).2 l)) a =
62
+ firstFormCoordinates U (_,_) a
63
+ rw [pulledHint_apply,firstFormCoordinates_apply]
64
+ simp only [hiddenSet,decide_eq_true_eq,rawPositions]
65
+ simp_rw [raw_slot_expansion U H.val w a]
66
+ simp only [Finset.sum_add_distrib,JointForms.affineOutput,JointForms.offset,Pi.add_apply]
67
+ ring
68
+
69
+ end MinUncut.Outer
70
+
71
+ end
72
+ end
73
+
74
+ end OAI
lean/OAI/Computability/MinUncut/Games/JointInner.lean ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.SelectedProject
3
+
4
+ namespace OAI
5
+
6
+ noncomputable section
7
+ open scoped BigOperators
8
+ open MeasureTheory ProbabilityTheory Filter
9
+ open scoped Topology NNReal
10
+ open scoped BigOperators
11
+ open MeasureTheory ProbabilityTheory Polynomial Filter
12
+ open scoped BigOperators Topology
13
+ open MeasureTheory ProbabilityTheory WithLp
14
+ open scoped BigOperators RealInnerProductSpace
15
+ open scoped BigOperators
16
+ namespace MinUncut.RowNoise
17
+ open MeasureTheory ProbabilityTheory BinaryFourier GaussianHermite
18
+ open scoped BigOperators
19
+ local instance jointInnerDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] :
20
+ Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintype
21
+ variable {R W ι : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W]
22
+ [AddCommGroup W] [Module F₂ W] [Fintype ι]
23
+
24
+ lemma maskProject_selfadjoint (S : Finset R) (f g : (R → W) → ℝ) :
25
+ (𝔼 B, f B * maskProject S g B) = 𝔼 B, maskProject S f B * g B := by
26
+ rw [← parseval_inner, ← parseval_inner]
27
+ simp only [coefficient_maskProject]
28
+ apply Finset.sum_congr rfl
29
+ intro α _
30
+ split_ifs <;> ring
31
+
32
+ lemma maskProject_idempotent (S T : Finset R) (f : (R → W) → ℝ) (B : R → W) :
33
+ maskProject S (maskProject T f) B = if S=T then maskProject S f B else 0 := by
34
+ rw [maskProject_expansion]
35
+ simp only [coefficient_maskProject]
36
+ by_cases h : S=T
37
+ · subst T
38
+ simp only [↓reduceIte]
39
+ rw [maskProject_expansion]
40
+ apply Finset.sum_congr rfl
41
+ intro α _
42
+ split_ifs <;> simp
43
+ · rw [ite_eq_right h]
44
+ apply Finset.sum_eq_zero
45
+ intro α _
46
+ split_ifs with hS hT
47
+ · exact (h (hS.symm.trans hT)).elim
48
+ · simp
49
+ · rfl
50
+
51
+ lemma maskProject_inner (S T : Finset R) (f g : (R → W) → ℝ) :
52
+ (𝔼 B, maskProject S f B * maskProject T g B) =
53
+ if S=T then (𝔼 B, f B * maskProject S g B) else 0 := by
54
+ rw [← maskProject_selfadjoint]
55
+ simp_rw [maskProject_idempotent]
56
+ split_ifs with h
57
+ · rfl
58
+ · simp
59
+
60
+ omit [AddCommGroup W] [Module F₂ W] in
61
+ lemma maskHermite_eq (S : Finset R) (I : ι → ℕ) (u : (R → W) → (ι → ℝ) → ℝ)
62
+ (B : R → W) (c : ι → ℝ) :
63
+ maskHermite S I u B c = psi I c * maskProject S (fun D => GaussianHermite.coeff (u D) I) B := by
64
+ unfold maskHermite maskProject hermiteComponent GaussianHermite.coeff
65
+ simp only [mul_left_comm _ (psi I c), ← Finset.mul_expect]
66
+
67
+ def jointInner (u v : (R → W) → (ι → ℝ) → ℝ) : ℝ :=
68
+ 𝔼 B, ∫ c, u B c * v B c ∂γpi ι
69
+
70
+ def jointEnergy (u : (R → W) → (ι → ℝ) → ℝ) : ℝ :=
71
+ 𝔼 B, ∫ c, (u B c)^2 ∂γpi ι
72
+
73
+ omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] in
74
+ lemma jointEnergy_nonneg (u : (R → W) → (ι → ℝ) → ℝ) : 0 ≤ jointEnergy u :=
75
+ Finset.expect_nonneg (fun _ _ => integral_nonneg (fun _ => sq_nonneg _))
76
+
77
+ omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] in
78
+ lemma jointInner_self (u : (R → W) → (ι → ℝ) → ℝ) : jointInner u u = jointEnergy u := by
79
+ simp only [jointInner, jointEnergy, pow_two]
80
+
81
+ omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] in
82
+ lemma jointInner_symm (u v : (R → W) → (ι → ℝ) → ℝ) : jointInner u v = jointInner v u := by
83
+ simp only [jointInner, mul_comm]
84
+
85
+ lemma jointInner_maskHermite (S T : Finset R) (I J : ι → ℕ)
86
+ (u v : (R → W) → (ι → ℝ) → ℝ) :
87
+ jointInner (maskHermite S I u) (maskHermite T J v) =
88
+ if I=J then if S=T then
89
+ (𝔼 B, GaussianHermite.coeff (u B) I * maskProject S (fun D => GaussianHermite.coeff (v D) J) B) else 0 else 0 := by
90
+ classical
91
+ unfold jointInner
92
+ simp only [maskHermite_eq]
93
+ have h (B : R → W) : (∫ c, (psi I c * maskProject S (fun D => GaussianHermite.coeff (u D) I) B) *
94
+ (psi J c * maskProject T (fun D => GaussianHermite.coeff (v D) J) B) ∂γpi ι) =
95
+ (if I=J then 1 else 0) * (maskProject S (fun D => GaussianHermite.coeff (u D) I) B *
96
+ maskProject T (fun D => GaussianHermite.coeff (v D) J) B) := by
97
+ simp_rw [mul_mul_mul_comm (psi I _) _ (psi J _) _]
98
+ rw [integral_mul_const, psi_product]
99
+ simp_rw [h, ← Finset.mul_expect, maskProject_inner]
100
+ split_ifs <;> simp_all
101
+
102
+ lemma jointInner_source_component (S : Finset R) (I : ι → ℕ)
103
+ (u : (R → W) → (ι → ℝ) → ℝ) :
104
+ jointInner u (maskHermite S I u) = jointEnergy (maskHermite S I u) := by
105
+ rw [← jointInner_self, jointInner_maskHermite]
106
+ simp only [↓reduceIte]
107
+ unfold jointInner
108
+ apply Finset.expect_congr rfl
109
+ intro B _
110
+ simp only [maskHermite_eq, ← mul_assoc, integral_mul_const]
111
+ congr 1
112
+ unfold GaussianHermite.coeff
113
+ simp only [mul_comm]
114
+
115
+ lemma components_orthogonal (a b : Finset R × (ι → ℕ)) (hab : a ≠ b)
116
+ (u : (R → W) → (ι → ℝ) → ℝ) :
117
+ jointInner (maskHermite a.1 a.2 u) (maskHermite b.1 b.2 u) = 0 := by
118
+ rw [jointInner_maskHermite]
119
+ split_ifs with hI hS
120
+ · exact (hab (Prod.ext hS hI)).elim
121
+ · rfl
122
+ · rfl
123
+
124
+ omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] in
125
+ lemma jointInner_sum_right {T : Type*} (s : Finset T)
126
+ (u : (R → W) → (ι → ℝ) → ℝ) (v : T → (R → W) → (ι → ℝ) → ℝ)
127
+ (hu : ∀ B, MemLp (u B) 2 (γpi ι)) (hv : ∀ t ∈ s, ∀ B, MemLp (v t B) 2 (γpi ι)) :
128
+ jointInner u (fun B c => ∑ t ∈ s, v t B c) = ∑ t ∈ s, jointInner u (v t) := by
129
+ unfold jointInner
130
+ simp only [Finset.mul_sum]
131
+ have hh (B) : (∫ c, ∑ t ∈ s, u B c * v t B c ∂γpi ι) =
132
+ ∑ t ∈ s, ∫ c, u B c * v t B c ∂γpi ι :=
133
+ integral_finsetSum s (fun t ht => (hu B).integrable_mul (hv t ht B))
134
+ simp_rw [hh]
135
+ rw [Finset.expect_sum_comm]
136
+
137
+ omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] in
138
+ lemma jointInner_sum_left {T : Type*} (s : Finset T)
139
+ (u : T → (R → W) → (ι → ℝ) → ℝ) (v : (R → W) → (ι → ℝ) → ℝ)
140
+ (hu : ∀ t ∈ s, ∀ B, MemLp (u t B) 2 (γpi ι)) (hv : ∀ B, MemLp (v B) 2 (γpi ι)) :
141
+ jointInner (fun B c => ∑ t ∈ s, u t B c) v = ∑ t ∈ s, jointInner (u t) v := by
142
+ rw [jointInner_symm, jointInner_sum_right s v u hv hu]
143
+ exact Finset.sum_congr rfl (fun t _ => jointInner_symm _ _)
144
+
145
+ lemma selectedProject_source_inner (J : Finset (Finset R × (ι → ℕ)))
146
+ (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) :
147
+ jointInner u (selectedProject J u) = ∑ j ∈ J, jointEnergy (maskHermite j.1 j.2 u) := by
148
+ change jointInner u (fun B c => ∑ j ∈ J, maskHermite j.1 j.2 u B c) = _
149
+ rw [jointInner_sum_right J u _ hu (fun j _ B => memLp_maskHermite _ _ _ B)]
150
+ exact Finset.sum_congr rfl (fun j _ => jointInner_source_component j.1 j.2 u)
151
+
152
+ lemma selectedProject_energy (J : Finset (Finset R × (ι → ℕ)))
153
+ (u : (R → W) → (ι → ℝ) → ℝ) :
154
+ jointEnergy (selectedProject J u) = ∑ j ∈ J, jointEnergy (maskHermite j.1 j.2 u) := by
155
+ classical
156
+ rw [← jointInner_self]
157
+ change jointInner (fun B c => ∑ j ∈ J, maskHermite j.1 j.2 u B c) (selectedProject J u) = _
158
+ rw [jointInner_sum_left J _ _ (fun j _ B => memLp_maskHermite _ _ _ B) (memLp_selectedProject J u)]
159
+ apply Finset.sum_congr rfl
160
+ intro j hj
161
+ change jointInner (maskHermite j.1 j.2 u) (fun B c => ∑ k ∈ J, maskHermite k.1 k.2 u B c) = _
162
+ rw [jointInner_sum_right J _ _ (memLp_maskHermite _ _ _) (fun k _ B => memLp_maskHermite _ _ _ B)]
163
+ rw [Finset.sum_eq_single j]
164
+ · exact jointInner_self _
165
+ · intro k hk hkj
166
+ exact components_orthogonal j k hkj.symm u
167
+ · exact fun hjn => (hjn hj).elim
168
+
169
+ omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] in
170
+ lemma jointEnergy_sub (u v : (R → W) → (ι → ℝ) → ℝ)
171
+ (hu : ∀ B, MemLp (u B) 2 (γpi ι)) (hv : ∀ B, MemLp (v B) 2 (γpi ι)) :
172
+ jointEnergy (fun B c => u B c-v B c) = jointEnergy u - 2*jointInner u v + jointEnergy v := by
173
+ have h (B) : (∫ c, (u B c-v B c)^2 ∂γpi ι) =
174
+ (∫ c, (u B c)^2 ∂γpi ι) - 2*(∫ c, u B c*v B c ∂γpi ι) + ∫ c, (v B c)^2 ∂γpi ι := by
175
+ simp only [sub_sq, mul_assoc]
176
+ have huv : Integrable (fun c => 2*(u B c*v B c)) (γpi ι) := ((hu B).integrable_mul (hv B)).const_mul 2
177
+ have hsub : Integrable (fun c => (u B c)^2-2*(u B c*v B c)) (γpi ι) := (hu B).integrable_sq.sub huv
178
+ rw [integral_add hsub (hv B).integrable_sq, integral_sub (hu B).integrable_sq huv, integral_const_mul]
179
+ simp only [jointEnergy, jointInner, h, Finset.expect_add_distrib, Finset.expect_sub_distrib, ← Finset.mul_expect]
180
+
181
+ theorem selectedProject_energy_le (J : Finset (Finset R × (ι → ℕ)))
182
+ (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) :
183
+ jointEnergy (selectedProject J u) ≤ jointEnergy u := by
184
+ have h := jointEnergy_nonneg (fun B c => u B c-selectedProject J u B c)
185
+ rw [jointEnergy_sub u _ hu (memLp_selectedProject J u), selectedProject_source_inner J u hu,
186
+ ← selectedProject_energy] at h
187
+ linarith
188
+
189
+ omit [AddCommGroup W] [Module F₂ W] in
190
+ lemma selectedProject_sdiff (J K : Finset (Finset R × (ι → ℕ))) (hK : K ⊆ J)
191
+ (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) (c : ι → ℝ) :
192
+ selectedProject J u B c-selectedProject K u B c = selectedProject (J\K) u B c := by
193
+ classical
194
+ unfold selectedProject
195
+ have h := Finset.sum_sdiff hK (f := fun j => maskHermite j.1 j.2 u B c)
196
+ linarith
197
+
198
+ lemma selectedProject_loss_energy (J K : Finset (Finset R × (ι → ℕ))) (hK : K ⊆ J)
199
+ (u : (R → W) → (ι → ℝ) → ℝ) :
200
+ jointEnergy (fun B c => selectedProject J u B c-selectedProject K u B c) =
201
+ ∑ j ∈ J\K, jointEnergy (maskHermite j.1 j.2 u) := by
202
+ simp_rw [selectedProject_sdiff J K hK]
203
+ exact selectedProject_energy _ u
204
+ end MinUncut.RowNoise
205
+
206
+ end
207
+
208
+ end OAI
lean/OAI/Computability/MinUncut/Games/KernelSampling.lean ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.OuterQuestions
3
+
4
+ namespace OAI
5
+
6
+ namespace MinUncutGames.Foundations.Games
7
+
8
+ open scoped BigOperators
9
+ noncomputable section
10
+
11
+ namespace FiniteDistribution
12
+
13
+ theorem pushforward_eq_of_agree_on_support
14
+ {Ω Γ : Type*} [Fintype Ω] [Fintype Γ]
15
+ (μ : FiniteDistribution Ω) (f g : Ω → Γ)
16
+ (h : ∀ x, μ.weight x ≠ 0 → f x = g x) :
17
+ μ.pushforward f = μ.pushforward g := by
18
+ classical
19
+ apply eq_of_weight_eq
20
+ intro y
21
+ simp only [pushforward]
22
+ apply Finset.sum_congr rfl
23
+ intro x _
24
+ by_cases hx : μ.weight x = 0
25
+ · simp [hx]
26
+ · rw [h x hx]
27
+
28
+ theorem product_pushforward
29
+ {Ω Γ A B : Type*} [Fintype Ω] [Fintype Γ] [Fintype A] [Fintype B]
30
+ (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ)
31
+ (f : Ω → A) (g : Γ → B) :
32
+ (μ.product ν).pushforward (fun z => (f z.1, g z.2)) =
33
+ (μ.pushforward f).product (ν.pushforward g) := by
34
+ classical
35
+ apply eq_of_weight_eq
36
+ rintro ⟨a, b⟩
37
+ simp only [pushforward, product]
38
+ rw [Fintype.sum_prod_type, Finset.sum_mul_sum]
39
+ apply Finset.sum_congr rfl
40
+ intro x _
41
+ apply Finset.sum_congr rfl
42
+ intro y _
43
+ by_cases hx : f x = a <;> by_cases hy : g y = b <;> simp [hx, hy]
44
+
45
+ theorem table_row_weight_ne_zero
46
+ {Q A : Type*} [Fintype Q] [Fintype A] [DecidableEq Q]
47
+ (responses : Q → FiniteDistribution A) (answers : Q → A)
48
+ (h : (table responses).weight answers ≠ 0) (q : Q) :
49
+ (responses q).weight (answers q) ≠ 0 := by
50
+ intro hq
51
+ apply h
52
+ change (∏ r, (responses r).weight (answers r)) = 0
53
+ exact Finset.prod_eq_zero (Finset.mem_univ q) hq
54
+
55
+ theorem table_repair_pushforward
56
+ {Q A : Type*} [Fintype Q] [Fintype A] [DecidableEq Q]
57
+ (responses : Q → FiniteDistribution A) (repair : Q → A → A)
58
+ (hrepair : ∀ q a, (responses q).weight a ≠ 0 → repair q a = a) (q : Q) :
59
+ (table responses).pushforward (fun answers => repair q (answers q)) =
60
+ responses q := by
61
+ calc
62
+ _ = (table responses).pushforward (fun answers => answers q) := by
63
+ apply pushforward_eq_of_agree_on_support
64
+ intro answers h
65
+ exact hrepair q (answers q) (table_row_weight_ne_zero responses answers h q)
66
+ _ = responses q := table_eval_pushforward responses q
67
+
68
+ end FiniteDistribution
69
+
70
+ namespace KernelSampling
71
+
72
+ abbrev Seed (Q₁ Q₂ A B : Type*) := (Q₁ → A) × (Q₂ → B)
73
+
74
+ def readLeft {Q₁ Q₂ A B : Type*} (seed : Seed Q₁ Q₂ A B) (q : Q₁) : A := seed.1 q
75
+ def readRight {Q₁ Q₂ A B : Type*} (seed : Seed Q₁ Q₂ A B) (q : Q₂) : B := seed.2 q
76
+
77
+ def seedLaw {Q₁ Q₂ A B : Type*}
78
+ [Fintype Q₁] [Fintype Q₂] [Fintype A] [Fintype B]
79
+ [DecidableEq Q₁] [DecidableEq Q₂]
80
+ (left : Q₁ → FiniteDistribution A) (right : Q₂ → FiniteDistribution B) :
81
+ FiniteDistribution (Seed Q₁ Q₂ A B) :=
82
+ (FiniteDistribution.table left).product (FiniteDistribution.table right)
83
+
84
+ theorem read_joint_pushforward {Q₁ Q₂ A B : Type*}
85
+ [Fintype Q₁] [Fintype Q₂] [Fintype A] [Fintype B]
86
+ [DecidableEq Q₁] [DecidableEq Q₂]
87
+ (left : Q₁ → FiniteDistribution A) (right : Q₂ → FiniteDistribution B)
88
+ (x : Q₁) (y : Q₂) :
89
+ (seedLaw left right).pushforward (fun seed => (readLeft seed x, readRight seed y)) =
90
+ (left x).product (right y) := by
91
+ unfold seedLaw readLeft readRight
92
+ rw [FiniteDistribution.product_pushforward
93
+ (FiniteDistribution.table left) (FiniteDistribution.table right)
94
+ (fun answers => answers x) (fun answers => answers y),
95
+ FiniteDistribution.table_eval_pushforward, FiniteDistribution.table_eval_pushforward]
96
+
97
+ theorem repaired_joint_pushforward {Q₁ Q₂ A B : Type*}
98
+ [Fintype Q₁] [Fintype Q₂] [Fintype A] [Fintype B]
99
+ [DecidableEq Q₁] [DecidableEq Q₂]
100
+ (left : Q₁ → FiniteDistribution A) (right : Q₂ → FiniteDistribution B)
101
+ (repairLeft : Q₁ → A → A) (repairRight : Q₂ → B → B)
102
+ (hleft : ∀ x a, (left x).weight a ≠ 0 → repairLeft x a = a)
103
+ (hright : ∀ y b, (right y).weight b ≠ 0 → repairRight y b = b)
104
+ (x : Q₁) (y : Q₂) :
105
+ (seedLaw left right).pushforward (fun seed =>
106
+ (repairLeft x (readLeft seed x), repairRight y (readRight seed y))) =
107
+ (left x).product (right y) := by
108
+ unfold seedLaw readLeft readRight
109
+ rw [FiniteDistribution.product_pushforward
110
+ (FiniteDistribution.table left) (FiniteDistribution.table right)
111
+ (fun answers => repairLeft x (answers x)) (fun answers => repairRight y (answers y)),
112
+ FiniteDistribution.table_repair_pushforward left repairLeft hleft,
113
+ FiniteDistribution.table_repair_pushforward right repairRight hright]
114
+
115
+ variable {I A B S : Type*} [DecidableEq I]
116
+
117
+ def completedLeft (j : I)
118
+ (seed : Seed (A × S) (B × S) (I → A) (I → B)) (q : A × S) : I → A :=
119
+ Function.update (readLeft seed q) j q.1
120
+
121
+ def completedRight (j : I)
122
+ (seed : Seed (A × S) (B × S) (I → A) (I → B)) (q : B × S) : I → B :=
123
+ Function.update (readRight seed q) j q.1
124
+
125
+ @[simp] theorem completedLeft_coordinate (j : I)
126
+ (seed : Seed (A × S) (B × S) (I → A) (I → B)) (q : A × S) :
127
+ completedLeft j seed q j = q.1 := by simp [completedLeft]
128
+
129
+ @[simp] theorem completedRight_coordinate (j : I)
130
+ (seed : Seed (A × S) (B × S) (I → A) (I → B)) (q : B × S) :
131
+ completedRight j seed q j = q.1 := by simp [completedRight]
132
+
133
+ private theorem update_eq_of_coordinate (xs : I → A) (j : I) (a : A)
134
+ (h : xs j = a) : Function.update xs j a = xs := by
135
+ funext i
136
+ by_cases hi : i = j <;> simp [Function.update, hi, h]
137
+
138
+ theorem completed_joint_pushforward
139
+ [Fintype I] [Fintype A] [Fintype B] [Fintype S]
140
+ [DecidableEq A] [DecidableEq B] [DecidableEq S]
141
+ (left : (A × S) → FiniteDistribution (I → A))
142
+ (right : (B × S) → FiniteDistribution (I → B)) (j : I)
143
+ (hleft : ∀ q xs, (left q).weight xs ≠ 0 → xs j = q.1)
144
+ (hright : ∀ q ys, (right q).weight ys ≠ 0 → ys j = q.1)
145
+ (x : A × S) (y : B × S) :
146
+ (seedLaw left right).pushforward
147
+ (fun seed => (completedLeft j seed x, completedRight j seed y)) =
148
+ (left x).product (right y) := by
149
+ apply repaired_joint_pushforward left right
150
+ (fun q xs => Function.update xs j q.1) (fun q ys => Function.update ys j q.1)
151
+ · intro q xs h
152
+ exact update_eq_of_coordinate xs j q.1 (hleft q xs h)
153
+ · intro q ys h
154
+ exact update_eq_of_coordinate ys j q.1 (hright q ys h)
155
+
156
+ end KernelSampling
157
+ end
158
+ end MinUncutGames.Foundations.Games
159
+
160
+ namespace MinUncutGames.Foundations.Games.FiniteDistribution
161
+
162
+ open scoped BigOperators
163
+ noncomputable section
164
+
165
+ variable {Seed Ω : Type*} [Fintype Seed] [Fintype Ω]
166
+
167
+ def mixture (seedLaw : FiniteDistribution Seed)
168
+ (laws : Seed → FiniteDistribution Ω) : FiniteDistribution Ω where
169
+ weight x := ∑ seed, seedLaw.weight seed * (laws seed).weight x
170
+ nonnegative x := Finset.sum_nonneg fun seed _ =>
171
+ mul_nonneg (seedLaw.nonnegative seed) ((laws seed).nonnegative x)
172
+ normalized := by
173
+ rw [Finset.sum_comm]
174
+ simp_rw [← Finset.mul_sum, (laws _).normalized, mul_one]
175
+ exact seedLaw.normalized
176
+
177
+ theorem probability_mixture (seedLaw : FiniteDistribution Seed)
178
+ (laws : Seed → FiniteDistribution Ω) (event : Ω → Bool) :
179
+ (seedLaw.mixture laws).probability event =
180
+ ∑ seed, seedLaw.weight seed * (laws seed).probability event := by
181
+ unfold probability mixture
182
+ calc
183
+ _ = ∑ x, ∑ seed,
184
+ seedLaw.weight seed * (if event x then (laws seed).weight x else 0) := by
185
+ apply Finset.sum_congr rfl
186
+ intro x _
187
+ cases event x <;> simp
188
+ _ = _ := by
189
+ rw [Finset.sum_comm]
190
+ apply Finset.sum_congr rfl
191
+ intro seed _
192
+ rw [Finset.mul_sum]
193
+
194
+ theorem probability_mixture_le (seedLaw : FiniteDistribution Seed)
195
+ (laws : Seed → FiniteDistribution Ω) (event : Ω → Bool) (bound : ℝ)
196
+ (h : ∀ seed, (laws seed).probability event ≤ bound) :
197
+ (seedLaw.mixture laws).probability event ≤ bound := by
198
+ rw [probability_mixture]
199
+ calc
200
+ _ ≤ ∑ seed, seedLaw.weight seed * bound :=
201
+ Finset.sum_le_sum fun seed _ =>
202
+ mul_le_mul_of_nonneg_left (h seed) (seedLaw.nonnegative seed)
203
+ _ = bound := by rw [← Finset.sum_mul, seedLaw.normalized, one_mul]
204
+
205
+ end
206
+ end MinUncutGames.Foundations.Games.FiniteDistribution
207
+
208
+ end OAI
lean/OAI/Computability/MinUncut/Games/LabelBound.lean ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.Basic
3
+
4
+ namespace OAI
5
+
6
+ namespace MinUncutGames.Foundations.CorrelatedSampling
7
+
8
+ noncomputable section
9
+
10
+ variable {σ α : Type*} [Fintype σ] [DecidableEq σ] [DecidableEq α]
11
+
12
+ def localSample (accept : σ → Bool) (decode : σ → α) (fallback : α)
13
+ (proposals : List σ) : α :=
14
+ ((firstAccepted accept proposals).map decode).getD fallback
15
+
16
+ def localDiagonal (left right : σ → Bool) (decode : σ → α) (fallback a : α)
17
+ (proposals : List σ) : ℝ :=
18
+ if localSample left decode fallback proposals = a ∧
19
+ localSample right decode fallback proposals = a then 1 else 0
20
+
21
+ def goodLabel (left right : σ → Bool) (decode : σ → α) (a : α) (s : σ) : Bool :=
22
+ (left s && right s) && decide (decode s = a)
23
+
24
+ omit [Fintype σ] [DecidableEq σ] in
25
+ theorem common_first_label_lower (left right : σ → Bool) (decode : σ → α)
26
+ (fallback a : α) (proposals : List σ) :
27
+ goodFirstIndicator (fun s => left s || right s) (goodLabel left right decode a) proposals ≤
28
+ localDiagonal left right decode fallback a proposals := by
29
+ cases hfirst : firstAccepted (fun s => left s || right s) proposals with
30
+ | none =>
31
+ simp only [goodFirstIndicator, hfirst]
32
+ unfold localDiagonal
33
+ split_ifs <;> norm_num
34
+ | some s =>
35
+ by_cases hc : goodLabel left right decode a s = true
36
+ · have hparts : (left s = true ∧ right s = true) ∧ decode s = a := by
37
+ simpa [goodLabel] using hc
38
+ have h := first_union_common left right proposals s hfirst hparts.1.1 hparts.1.2
39
+ simp [goodFirstIndicator, hfirst, hc, localDiagonal, localSample, h.1, h.2, hparts.2]
40
+ · have hn : 0 ≤ localDiagonal left right decode fallback a proposals := by
41
+ unfold localDiagonal
42
+ split_ifs <;> norm_num
43
+ simpa [goodFirstIndicator, hfirst, hc] using hn
44
+
45
+ omit [DecidableEq σ] in theorem union_goodLabel_mass
46
+ (w : σ → ℝ) (left right : σ → Bool) (decode : σ → α) (a : α) :
47
+ eventMass w (fun s => (left s || right s) && goodLabel left right decode a s) =
48
+ eventMass w (goodLabel left right decode a) := by
49
+ unfold eventMass
50
+ apply Finset.sum_congr rfl
51
+ intro s _
52
+ cases hl : left s <;> cases hr : right s <;> simp [goodLabel, hl, hr]
53
+
54
+ theorem finite_label_diagonal_bound (w : σ → ℝ) (left right : σ → Bool)
55
+ (decode : σ → α) (fallback a : α) (hw : ∀ s, 0 ≤ w s)
56
+ (hw_sum : ∑ s, w s = 1) (hu : 0 < eventMass w (fun s => left s || right s)) (n : Nat) :
57
+ eventMass w (goodLabel left right decode a) / eventMass w (fun s => left s || right s) *
58
+ (1 - eventMass w (fun s => !(left s || right s)) ^ n) ≤
59
+ traceAverage w n (localDiagonal left right decode fallback a) := by
60
+ have h := traceAverage_mono w hw n _ _ (common_first_label_lower left right decode fallback a)
61
+ rw [goodFirstIndicator_law w _ _ hw_sum n,
62
+ goodFirstMass_exact w _ _ hw_sum (ne_of_gt hu) n,
63
+ union_goodLabel_mass] at h
64
+ exact h
65
+
66
+ variable [Fintype α] [Nonempty α]
67
+
68
+ theorem rectangle_label_diagonal_bound (thresholds : List ℝ) (p q : α → ℝ)
69
+ (fallback a : α)
70
+ (hpm : ∀ x, p x ∈ thresholds) (hqm : ∀ x, q x ∈ thresholds)
71
+ (hp0 : ∀ x, 0 ≤ p x) (hq0 : ∀ x, 0 ≤ q x)
72
+ (hp1 : ∀ x, p x ≤ 1) (hq1 : ∀ x, q x ≤ 1)
73
+ (hpsum : ∑ x, p x = 1) (hqsum : ∑ x, q x = 1) (n : Nat) :
74
+ min (p a) (q a) / (1 + totalVariation p q) *
75
+ (1 - eventMass (rectangleWeight thresholds)
76
+ (fun s => !(rectangleAccept thresholds p s || rectangleAccept thresholds q s)) ^ n) ≤
77
+ traceAverage (rectangleWeight thresholds) n
78
+ (localDiagonal (rectangleAccept thresholds p) (rectangleAccept thresholds q)
79
+ Prod.fst fallback a) := by
80
+ have hc : 0 < (Fintype.card α : ℝ) := by exact_mod_cast Fintype.card_pos
81
+ have hU : 0 < unionMass p q := by
82
+ rw [unionMass_eq p q hpsum hqsum]
83
+ linarith [totalVariation_nonneg p q]
84
+ have hmass := rectangle_union_mass thresholds p q hpm hqm hp0 hq0 hp1 hq1
85
+ have hu : 0 < eventMass (rectangleWeight thresholds)
86
+ (fun s => rectangleAccept thresholds p s || rectangleAccept thresholds q s) := by
87
+ rw [hmass]
88
+ exact div_pos hU hc
89
+ have h := finite_label_diagonal_bound (rectangleWeight thresholds)
90
+ (rectangleAccept thresholds p) (rectangleAccept thresholds q) Prod.fst fallback a
91
+ (rectangleWeight_nonnegative thresholds) (rectangleWeight_normalized thresholds) hu n
92
+ unfold goodLabel at h
93
+ rw [rectangle_common_label_mass thresholds p q a hpm hqm hp0 hq0 hp1 hq1, hmass] at h
94
+ have hratio : (min (p a) (q a) / (Fintype.card α : ℝ)) /
95
+ (unionMass p q / (Fintype.card α : ℝ)) = min (p a) (q a) / unionMass p q := by
96
+ field_simp
97
+ rw [hratio, unionMass_eq p q hpsum hqsum] at h
98
+ exact h
99
+
100
+ end
101
+
102
+ open scoped BigOperators
103
+
104
+ noncomputable section
105
+
106
+ def profileThresholds {κ S : Type*} [Fintype κ] [Fintype S]
107
+ (P : κ → S → ℝ) : List ℝ := by
108
+ classical
109
+ exact (Finset.univ.toList : List (κ × S)).map (fun ks => P ks.1 ks.2)
110
+
111
+ theorem mem_profileThresholds {κ S : Type*} [Fintype κ] [Fintype S]
112
+ (P : κ → S → ℝ) (k : κ) (s : S) : P k s ∈ profileThresholds P := by
113
+ classical
114
+ exact List.mem_map.mpr ⟨(k, s), by simp, rfl⟩
115
+
116
+ theorem distribution_weight_le_one {S : Type*} [Fintype S]
117
+ (μ : Games.FiniteDistribution S) (s : S) : μ.weight s ≤ 1 := by
118
+ calc
119
+ μ.weight s ≤ ∑ t, μ.weight t :=
120
+ Finset.single_le_sum (fun t _ => μ.nonnegative t) (Finset.mem_univ s)
121
+ _ = 1 := μ.normalized
122
+
123
+ variable {Q₁ Q₂ S : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype S]
124
+
125
+ def sharedProfileThresholds (L : Q₁ → Games.FiniteDistribution S)
126
+ (R : Q₂ → Games.FiniteDistribution S) : List ℝ :=
127
+ profileThresholds (fun (k : Q₁ ⊕ Q₂) s => (Sum.elim L R k).weight s)
128
+
129
+ theorem left_mem_sharedProfileThresholds (L : Q₁ → Games.FiniteDistribution S)
130
+ (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) (s : S) :
131
+ (L x).weight s ∈ sharedProfileThresholds L R := by
132
+ exact mem_profileThresholds _ (Sum.inl x) s
133
+
134
+ theorem right_mem_sharedProfileThresholds (L : Q₁ → Games.FiniteDistribution S)
135
+ (R : Q₂ → Games.FiniteDistribution S) (y : Q₂) (s : S) :
136
+ (R y).weight s ∈ sharedProfileThresholds L R := by
137
+ exact mem_profileThresholds _ (Sum.inr y) s
138
+
139
+ abbrev SharedProfileSeed (L : Q₁ → Games.FiniteDistribution S)
140
+ (R : Q₂ → Games.FiniteDistribution S) :=
141
+ RectangleSeed (sharedProfileThresholds L R) S
142
+
143
+ def sharedProfileLeft (L : Q₁ → Games.FiniteDistribution S)
144
+ (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) : SharedProfileSeed L R → Bool :=
145
+ rectangleAccept (sharedProfileThresholds L R) (L x).weight
146
+
147
+ def sharedProfileRight (L : Q₁ → Games.FiniteDistribution S)
148
+ (R : Q₂ → Games.FiniteDistribution S) (y : Q₂) : SharedProfileSeed L R → Bool :=
149
+ rectangleAccept (sharedProfileThresholds L R) (R y).weight
150
+
151
+ def sharedProfileReject (L : Q₁ → Games.FiniteDistribution S)
152
+ (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) (y : Q₂) : ℝ :=
153
+ eventMass (rectangleWeight (sharedProfileThresholds L R))
154
+ (fun s => !(sharedProfileLeft L R x s || sharedProfileRight L R y s))
155
+
156
+ def uniformRejectionRate (S : Type*) [Fintype S] : ℝ :=
157
+ 1 - 1 / (Fintype.card S : ℝ)
158
+
159
+ theorem uniformRejectionRate_nonnegative (S : Type*) [Fintype S] [Nonempty S] :
160
+ 0 ≤ uniformRejectionRate S := by
161
+ have hc : (0 : ℝ) < Fintype.card S := by
162
+ exact_mod_cast (Fintype.card_pos : 0 < Fintype.card S)
163
+ have hc₁ : (1 : ℝ) ≤ Fintype.card S := by
164
+ exact_mod_cast (Nat.succ_le_of_lt (Fintype.card_pos : 0 < Fintype.card S))
165
+ apply sub_nonneg.mpr
166
+ exact (div_le_iff₀ hc).2 (by simpa using hc₁)
167
+
168
+ theorem uniformRejectionRate_lt_one (S : Type*) [Fintype S] [Nonempty S] :
169
+ uniformRejectionRate S < 1 := by
170
+ have hc : (0 : ℝ) < Fintype.card S := by
171
+ exact_mod_cast (Fintype.card_pos : 0 < Fintype.card S)
172
+ have hp : (0 : ℝ) < 1 / (Fintype.card S : ℝ) := div_pos (by norm_num) hc
173
+ dsimp [uniformRejectionRate]
174
+ linarith
175
+
176
+ theorem sharedProfileReject_nonnegative [Nonempty S]
177
+ (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S)
178
+ (x : Q₁) (y : Q₂) : 0 ≤ sharedProfileReject L R x y := by
179
+ exact eventMass_nonneg _ _
180
+ (rectangleDistribution (α := S) (sharedProfileThresholds L R)).nonnegative
181
+
182
+ theorem sharedProfile_reject_le_rate [Nonempty S]
183
+ (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S)
184
+ (x : Q₁) (y : Q₂) : sharedProfileReject L R x y ≤ uniformRejectionRate S := by
185
+ let thresholds := sharedProfileThresholds L R
186
+ have hsum : (∑ s : RectangleSeed thresholds S, rectangleWeight thresholds s) = 1 :=
187
+ (rectangleDistribution (α := S) thresholds).normalized
188
+ have hcomp := eventMass_complement (rectangleWeight thresholds)
189
+ (fun s => sharedProfileLeft L R x s || sharedProfileRight L R y s) hsum
190
+ have hu : eventMass (rectangleWeight thresholds)
191
+ (fun s => sharedProfileLeft L R x s || sharedProfileRight L R y s) =
192
+ (1 + totalVariation (L x).weight (R y).weight) / (Fintype.card S : ℝ) := by
193
+ change eventMass (rectangleWeight thresholds)
194
+ (fun s => rectangleAccept thresholds (L x).weight s ||
195
+ rectangleAccept thresholds (R y).weight s) = _
196
+ rw [rectangle_union_mass thresholds (L x).weight (R y).weight
197
+ (left_mem_sharedProfileThresholds L R x)
198
+ (right_mem_sharedProfileThresholds L R y)
199
+ (L x).nonnegative (R y).nonnegative
200
+ (distribution_weight_le_one (L x)) (distribution_weight_le_one (R y))]
201
+ rw [unionMass_eq (L x).weight (R y).weight (L x).normalized (R y).normalized]
202
+ have hc : (0 : ℝ) < Fintype.card S := by
203
+ exact_mod_cast (Fintype.card_pos : 0 < Fintype.card S)
204
+ have htv := totalVariation_nonneg (L x).weight (R y).weight
205
+ have hquot : 1 / (Fintype.card S : ℝ) ≤
206
+ (1 + totalVariation (L x).weight (R y).weight) / (Fintype.card S : ℝ) :=
207
+ (div_le_div_iff_of_pos_right hc).2 (by linarith)
208
+ rw [hu] at hcomp
209
+ change eventMass (rectangleWeight thresholds)
210
+ (fun s => !(sharedProfileLeft L R x s || sharedProfileRight L R y s)) ≤
211
+ 1 - 1 / (Fintype.card S : ℝ)
212
+ linarith
213
+
214
+ private theorem nonnegative_powers_mono (a b : ℝ) (ha : 0 ≤ a) (hab : a ≤ b)
215
+ (n : ℕ) : a ^ n ≤ b ^ n := by
216
+ have hb : 0 ≤ b := le_trans ha hab
217
+ induction n with
218
+ | zero => simp
219
+ | succ n ih =>
220
+ rw [pow_succ, pow_succ]
221
+ exact mul_le_mul ih hab ha (pow_nonneg hb n)
222
+
223
+ theorem sharedProfile_label_diagonal_bound [Nonempty S] [DecidableEq S]
224
+ (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S)
225
+ (x : Q₁) (y : Q₂) (fallback a : S) (n : ℕ) :
226
+ min ((L x).weight a) ((R y).weight a) /
227
+ (1 + totalVariation (L x).weight (R y).weight) *
228
+ (1 - uniformRejectionRate S ^ n) ≤
229
+ traceAverage (rectangleWeight (sharedProfileThresholds L R)) n
230
+ (localDiagonal (sharedProfileLeft L R x) (sharedProfileRight L R y)
231
+ Prod.fst fallback a) := by
232
+ have hp := nonnegative_powers_mono (sharedProfileReject L R x y)
233
+ (uniformRejectionRate S) (sharedProfileReject_nonnegative L R x y)
234
+ (sharedProfile_reject_le_rate L R x y) n
235
+ have htv := totalVariation_nonneg (L x).weight (R y).weight
236
+ have hm : 0 ≤ min ((L x).weight a) ((R y).weight a) /
237
+ (1 + totalVariation (L x).weight (R y).weight) :=
238
+ div_nonneg (le_min ((L x).nonnegative a) ((R y).nonnegative a)) (by linarith)
239
+ have hsurv :
240
+ min ((L x).weight a) ((R y).weight a) /
241
+ (1 + totalVariation (L x).weight (R y).weight) *
242
+ (1 - uniformRejectionRate S ^ n) ≤
243
+ min ((L x).weight a) ((R y).weight a) /
244
+ (1 + totalVariation (L x).weight (R y).weight) *
245
+ (1 - sharedProfileReject L R x y ^ n) :=
246
+ mul_le_mul_of_nonneg_left (by linarith) hm
247
+ refine hsurv.trans ?_
248
+ simpa only [sharedProfileReject, sharedProfileLeft, sharedProfileRight] using
249
+ rectangle_label_diagonal_bound (sharedProfileThresholds L R)
250
+ (L x).weight (R y).weight fallback a
251
+ (left_mem_sharedProfileThresholds L R x)
252
+ (right_mem_sharedProfileThresholds L R y)
253
+ (L x).nonnegative (R y).nonnegative
254
+ (distribution_weight_le_one (L x)) (distribution_weight_le_one (R y))
255
+ (L x).normalized (R y).normalized n
256
+
257
+ theorem exists_uniformRejectionRate_pow_lt (S : Type*) [Fintype S] [Nonempty S]
258
+ (η : ℝ) (hη : 0 < η) : ∃ n : ℕ, uniformRejectionRate S ^ n < η := by
259
+ have ht := tendsto_pow_atTop_nhds_zero_of_lt_one
260
+ (uniformRejectionRate_nonnegative S) (uniformRejectionRate_lt_one S)
261
+ exact (ht.eventually (gt_mem_nhds hη)).exists
262
+
263
+ end
264
+
265
+ end MinUncutGames.Foundations.CorrelatedSampling
266
+
267
+ end OAI
lean/OAI/Computability/MinUncut/Games/MaskRowKernel.lean ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.Density
3
+ import OAI.Computability.MinUncut.Estimates.Convolution
4
+
5
+ namespace OAI
6
+
7
+ noncomputable section
8
+ open scoped BigOperators
9
+ open MeasureTheory ProbabilityTheory Filter
10
+ open scoped Topology NNReal
11
+ open scoped BigOperators
12
+ open MeasureTheory ProbabilityTheory Polynomial Filter
13
+ open scoped BigOperators Topology
14
+ open MeasureTheory ProbabilityTheory WithLp
15
+ open scoped BigOperators RealInnerProductSpace
16
+ namespace MinUncut.RowNoise
17
+ open BinaryFourier
18
+ open scoped BigOperators
19
+ local instance maskRowKernelDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] :
20
+ Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintype
21
+ variable {R W : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W]
22
+ [AddCommGroup W] [Module F₂ W]
23
+
24
+ def maskRowKernel (active : Bool) (b c : W) : ℝ :=
25
+ if active then rowDensity 0 b c-1 else 1
26
+
27
+ omit [AddCommGroup W] [Module F₂ W] in
28
+ lemma maskRowKernel_symmetric (active : Bool) (b c : W) :
29
+ maskRowKernel active b c = maskRowKernel active c b := by
30
+ simp only [maskRowKernel, rowDensity_symmetric]
31
+
32
+ omit [Module F₂ W] in
33
+ lemma maskRowKernel_abs_mean (active : Bool) (b : W) :
34
+ (𝔼 c, |maskRowKernel active b c|) ≤ if active then 2 else 1 := by
35
+ cases active
36
+ · simp [maskRowKernel]
37
+ · dsimp only [maskRowKernel]
38
+ calc
39
+ _ ≤ 𝔼 c, (rowDensity 0 b c+1) := by
40
+ apply Finset.expect_le_expect
41
+ intro c _
42
+ exact (abs_sub _ _).trans (by rw [abs_of_nonneg (rowDensity_nonneg (by norm_num) (by norm_num) _ _), abs_one])
43
+ _ = 2 := by rw [Finset.expect_add_distrib, rowDensity_mean]; norm_num
44
+
45
+ lemma maskRowKernel_character (active : Bool) (b : W) (α : Module.Dual F₂ W) :
46
+ (𝔼 c, maskRowKernel active b c * character α c) =
47
+ if active = decide (α ≠ 0) then character α b else 0 := by
48
+ cases active
49
+ · simp [maskRowKernel, character_mean]
50
+ split_ifs with h
51
+ · simp [h]
52
+ · rfl
53
+ · simp only [maskRowKernel, ↓reduceIte, sub_mul, one_mul,
54
+ Finset.expect_sub_distrib, row_character_eigen, character_mean]
55
+ by_cases h : α=0 <;> simp [h]
56
+
57
+ def maskKernel (S : Finset R) (B C : R → W) : ℝ :=
58
+ ∏ r, maskRowKernel (decide (r ∈ S)) (B r) (C r)
59
+
60
+ omit [AddCommGroup W] [Module F₂ W] in
61
+ lemma maskKernel_symmetric (S : Finset R) (B C : R → W) :
62
+ maskKernel S B C = maskKernel S C B := by simp only [maskKernel, maskRowKernel_symmetric]
63
+
64
+ omit [Module F₂ W] in
65
+ lemma maskKernel_abs_mean (S : Finset R) (B : R → W) :
66
+ (𝔼 C, |maskKernel S B C|) ≤ (2 : ℝ)^Fintype.card R := by
67
+ simp only [maskKernel, Finset.abs_prod]
68
+ rw [expect_prod (f := fun r (c : W) => |maskRowKernel (decide (r ∈ S)) (B r) c|)]
69
+ calc
70
+ _ ≤ ∏ r : R, (2:ℝ) := by
71
+ apply Finset.prod_le_prod₀
72
+ · intro r _; exact Finset.expect_nonneg (fun _ _ => abs_nonneg _)
73
+ · intro r _
74
+ exact (maskRowKernel_abs_mean _ _).trans (by split_ifs <;> norm_num)
75
+ _ = _ := by simp
76
+
77
+ lemma maskKernel_character (S : Finset R) (B : R → W) (α : Module.Dual F₂ (R → W)) :
78
+ (𝔼 C, maskKernel S B C * character α C) = if mask α=S then character α B else 0 := by
79
+ simp only [maskKernel, character_product, ← Finset.prod_mul_distrib]
80
+ rw [expect_prod (f := fun r (c : W) => maskRowKernel (decide (r ∈ S)) (B r) c * character (frequency α r) c)]
81
+ simp only [maskRowKernel_character]
82
+ have he (r : R) : (decide (r ∈ S) = decide (frequency α r ≠ 0)) ↔
83
+ (r ∈ S ↔ r ∈ mask α) := by
84
+ by_cases h₁ : r ∈ S <;> by_cases h₂ : frequency α r=0 <;> simp [mask, h₁, h₂]
85
+ by_cases hs : mask α=S
86
+ · rw [ite_eq_left hs]
87
+ apply Finset.prod_congr rfl
88
+ intro r _
89
+ rw [ite_eq_left ((he r).mpr (by rw [hs]))]
90
+ · rw [ite_eq_right hs]
91
+ have hh : ∃ r, ¬(r ∈ S ↔ r ∈ mask α) := by
92
+ by_contra hn
93
+ push Not at hn
94
+ exact hs (Finset.ext (fun r => (hn r).symm))
95
+ obtain ⟨r,hr⟩ := hh
96
+ exact Finset.prod_eq_zero (Finset.mem_univ r) (ite_eq_right (fun h => hr ((he r).mp h)))
97
+
98
+ def maskProject (S : Finset R) (f : (R → W) → ℝ) (B : R → W) : ℝ :=
99
+ 𝔼 C, maskKernel S B C * f C
100
+
101
+ lemma maskProject_expansion (S : Finset R) (f : (R → W) → ℝ) (B : R → W) :
102
+ maskProject S f B = ∑ α : Module.Dual F₂ (R → W),
103
+ if mask α=S then coefficient f α * character α B else 0 := by
104
+ unfold maskProject
105
+ conv_lhs => arg 2; ext C; rw [← inversion f C]
106
+ simp only [Finset.mul_sum]
107
+ rw [Finset.expect_sum_comm]
108
+ apply Finset.sum_congr rfl
109
+ intro α _
110
+ simp_rw [mul_left_comm _ (coefficient f α), ← Finset.mul_expect, maskKernel_character]
111
+ split_ifs <;> simp
112
+
113
+ lemma coefficient_maskProject (S : Finset R) (f : (R → W) → ℝ) (α : Module.Dual F₂ (R → W)) :
114
+ coefficient (maskProject S f) α = if mask α=S then coefficient f α else 0 := by
115
+ have he (B : R → W) : maskProject S f B =
116
+ ∑ β ∈ Finset.univ.filter (fun β : Module.Dual F₂ (R → W) => mask β=S), coefficient f β*character β B := by
117
+ rw [maskProject_expansion, Finset.sum_filter]
118
+ unfold coefficient
119
+ simp_rw [he, Finset.sum_mul, Finset.expect_sum_comm, mul_assoc, ← Finset.mul_expect,
120
+ character_orthogonality]
121
+ simp [Finset.mem_filter, coefficient]
122
+
123
+ omit [Module F₂ W] in
124
+ lemma maskProject_l1 (S : Finset R) (f : (R → W) → ℝ) :
125
+ (𝔼 B, |maskProject S f B|) ≤ (2:ℝ)^Fintype.card R * (𝔼 B, |f B|) := by
126
+ calc
127
+ _ ≤ 𝔼 B, 𝔼 C, |maskKernel S B C| * |f C| := by
128
+ apply Finset.expect_le_expect
129
+ intro B _
130
+ simpa only [maskProject, abs_mul] using Finset.abs_expect_le Finset.univ (fun C => maskKernel S B C*f C)
131
+ _ = 𝔼 C, (𝔼 B, |maskKernel S C B|)*|f C| := by
132
+ rw [Finset.expect_comm]
133
+ simp only [maskKernel_symmetric, Finset.expect_mul]
134
+ _ ≤ 𝔼 C, (2:ℝ)^Fintype.card R * |f C| := by
135
+ apply Finset.expect_le_expect
136
+ intro C _
137
+ exact mul_le_mul_of_nonneg_right (maskKernel_abs_mean S C) (abs_nonneg _)
138
+ _ = _ := (Finset.mul_expect _ _ _).symm
139
+ end MinUncut.RowNoise
140
+
141
+ end
142
+
143
+ end OAI
lean/OAI/Computability/MinUncut/Games/OuterQuestions.lean ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Estimates.FaceUpdateSelf
3
+ import OAI.Computability.MinUncut.Games.AffineLabels
4
+ import OAI.Computability.MinUncut.Machines.OuterAlphabets
5
+
6
+ namespace OAI
7
+
8
+ noncomputable section
9
+ open scoped BigOperators
10
+ namespace MinUncut.Outer
11
+ open MinUncut.Inner
12
+ attribute [local instance] Classical.propDecidable
13
+ variable {Name I : Type*}
14
+
15
+ abbrev SecondQuestion (Name : Type*) := Name ⊕ Equation Name
16
+
17
+ def secondSlotCount : SecondQuestion Name → ℕ
18
+ | .inl _ => 1
19
+ | .inr _ => 3
20
+ abbrev secondSlot (v : SecondQuestion Name) := Fin (secondSlotCount v) → F₂
21
+
22
+ abbrev FirstAlphabet (U : I → Equation Name) := ∀ j, alphabet (U j)
23
+ abbrev FirstDirection (U : I → Equation Name) := ∀ j, (alphabet (U j)).direction
24
+ abbrev SecondAlphabet (V : I → SecondQuestion Name) := ∀ j, secondSlot (V j)
25
+
26
+ def slotQuestion (E : Equation Name) (hidden : Bool) (p : Fin 3) : SecondQuestion Name :=
27
+ if hidden then .inl (E.names p) else .inr E
28
+
29
+ def slotProjection (E : Equation Name) (hidden : Bool) (p : Fin 3) :
30
+ alphabet E →ᵃ[F₂] secondSlot (slotQuestion E hidden p) := by
31
+ cases hidden
32
+ · exact (alphabet E).subtype
33
+ · exact (LinearMap.pi (fun _ : Fin 1 => (LinearMap.proj p : Triple →ₗ[F₂] F₂))).toAffineMap.comp (alphabet E).subtype
34
+
35
+ def secondQuestion (U : I → Equation Name) (hidden : I → Bool) (position : I → Fin 3) :
36
+ I → SecondQuestion Name := fun j => slotQuestion (U j) (hidden j) (position j)
37
+
38
+ def projection (U : I → Equation Name) (hidden : I → Bool) (position : I → Fin 3) :
39
+ FirstAlphabet U →ᵃ[F₂] SecondAlphabet (secondQuestion U hidden position) :=
40
+ AffineMap.pi (fun j => (slotProjection (U j) (hidden j) (position j)).comp (AffineMap.proj j))
41
+
42
+ @[simp] lemma projection_apply (U : I → Equation Name) (hidden : I → Bool)
43
+ (position : I → Fin 3) (a : FirstAlphabet U) (j : I) :
44
+ projection U hidden position a j=slotProjection (U j) (hidden j) (position j) (a j) := rfl
45
+
46
+ def evaluatedTriple (s : Name → F₂) (E : Equation Name) : Triple := fun p => s (E.names p)
47
+ def Satisfied (s : Name → F₂) (E : Equation Name) : Prop := parity (evaluatedTriple s E)=E.rhs
48
+
49
+ lemma evaluatedTriple_valid (s : Name → F₂) (E : Equation Name) (h : Satisfied s E) :
50
+ Valid E (evaluatedTriple s E) :=
51
+ ⟨h,fun _ _ he => congrArg s he⟩
52
+
53
+ def firstLabel (s : Name → F₂) (U : I → Equation Name) : FirstAlphabet U :=
54
+ fun j => if h : Satisfied s (U j) then ⟨evaluatedTriple s (U j),evaluatedTriple_valid s (U j) h⟩
55
+ else origin (U j)
56
+
57
+ def secondSlotLabel (s : Name → F₂) : (v : SecondQuestion Name) → secondSlot v
58
+ | .inl x => fun _ => s x
59
+ | .inr E => evaluatedTriple s E
60
+
61
+ def secondLabel (s : Name → F₂) (V : I → SecondQuestion Name) : SecondAlphabet V :=
62
+ fun j => secondSlotLabel s (V j)
63
+
64
+ lemma honest_slot (s : Name → F₂) (E : Equation Name) (h : Satisfied s E)
65
+ (hidden : Bool) (p : Fin 3) :
66
+ slotProjection E hidden p ⟨evaluatedTriple s E,evaluatedTriple_valid s E h⟩ =
67
+ secondSlotLabel s (slotQuestion E hidden p) := by
68
+ cases hidden <;> rfl
69
+
70
+ lemma honest_projection (s : Name → F₂) (U : I → Equation Name)
71
+ (h : ∀ j, Satisfied s (U j)) (hidden : I → Bool) (position : I → Fin 3) :
72
+ projection U hidden position (firstLabel s U) =
73
+ secondLabel s (secondQuestion U hidden position) := by
74
+ funext j
75
+ change slotProjection (U j) (hidden j) (position j) (firstLabel s U j)=_
76
+ simp only [firstLabel,dite_eq_left (h j)]
77
+ exact honest_slot s (U j) (h j) (hidden j) (position j)
78
+
79
+ open MinUncut.Inner
80
+ attribute [local instance] Classical.propDecidable
81
+ variable {Name I : Type*} [Fintype I]
82
+
83
+ def slotFunctional (v : SecondQuestion Name) (β : F₂) (l : Module.Dual F₂ Triple) :
84
+ Module.Dual F₂ (secondSlot v) := by
85
+ cases v with
86
+ | inl x => exact β • (LinearMap.proj (0 : Fin 1))
87
+ | inr E => exact l
88
+
89
+ lemma slotFunctional_add (v : SecondQuestion Name) (β γ : F₂) (l k : Module.Dual F₂ Triple) :
90
+ slotFunctional v (β+γ) (l+k)=slotFunctional v β l + slotFunctional v γ k := by
91
+ cases v with
92
+ | inl x => exact add_smul _ _ _
93
+ | inr E => rfl
94
+
95
+ lemma slotFunctional_smul (v : SecondQuestion Name) (c β : F₂) (l : Module.Dual F₂ Triple) :
96
+ slotFunctional v (c • β) (c • l)=c • slotFunctional v β l := by
97
+ cases v with
98
+ | inl x =>
99
+ change (c*β) • (LinearMap.proj (0 : Fin 1) : Module.Dual F₂ (Fin 1 → F₂)) = _
100
+ exact mul_smul _ _ _
101
+ | inr E => rfl
102
+
103
+ def directLinear (V : I → SecondQuestion Name) (β : I → F₂)
104
+ (l : I → Module.Dual F₂ Triple) : Module.Dual F₂ (SecondAlphabet V) :=
105
+ ∑ j, (slotFunctional (V j) (β j) (l j)).comp (LinearMap.proj j)
106
+
107
+ def directHint (V : I → SecondQuestion Name) (κ : F₂) (β : I → F₂)
108
+ (l : I → Module.Dual F₂ Triple) : Forms (SecondAlphabet V) :=
109
+ (directLinear V β l).toAffineMap + AffineMap.const F₂ _ κ
110
+
111
+ @[simp] lemma directHint_apply (V : I → SecondQuestion Name) (κ : F₂) (β : I → F₂)
112
+ (l : I → Module.Dual F₂ Triple) (a : SecondAlphabet V) :
113
+ directHint V κ β l a = (∑ j, slotFunctional (V j) (β j) (l j) (a j))+κ := by
114
+ simp [directHint,directLinear]
115
+
116
+ lemma slotFunctional_project (E : Equation Name) (hidden : Bool) (p : Fin 3)
117
+ (β : F₂) (l : Module.Dual F₂ Triple) (a : alphabet E) :
118
+ slotFunctional (slotQuestion E hidden p) β l (slotProjection E hidden p a) =
119
+ if hidden then β*a.val p else l a.val := by
120
+ cases hidden <;> rfl
121
+
122
+ lemma pulledHint_apply (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3)
123
+ (κ : F₂) (β : I → F₂) (l : I → Module.Dual F₂ Triple) (a : FirstAlphabet U) :
124
+ formPullback (projection U hidden pos)
125
+ (directHint (secondQuestion U hidden pos) κ β l) a =
126
+ (∑ j, if hidden j then β j*(a j).val (pos j) else l j (a j).val)+κ := by
127
+ change directHint (secondQuestion U hidden pos) κ β l (projection U hidden pos a)=_
128
+ rw [directHint_apply]
129
+ congr 1
130
+ apply Finset.sum_congr rfl
131
+ intro j _
132
+ exact slotFunctional_project (U j) (hidden j) (pos j) (β j) (l j) (a j)
133
+
134
+ lemma pulledHint_independent_active (U : I → Equation Name) (hidden : I → Bool)
135
+ (pos pos' : I → Fin 3) (κ : F₂) (β : I → F₂) (l : I → Module.Dual F₂ Triple)
136
+ (h : ∀ j, hidden j=true → pos j≠pos' j → β j=0) :
137
+ formPullback (projection U hidden pos)
138
+ (directHint (secondQuestion U hidden pos) κ β l) =
139
+ formPullback (projection U hidden pos')
140
+ (directHint (secondQuestion U hidden pos') κ β l) := by
141
+ ext a
142
+ rw [pulledHint_apply,pulledHint_apply]
143
+ congr 1
144
+ apply Finset.sum_congr rfl
145
+ intro j _
146
+ by_cases hh : hidden j=true
147
+ · simp only [hh,↓reduceIte]
148
+ by_cases hp : pos j=pos' j
149
+ · rw [hp]
150
+ · rw [h j hh hp]; simp
151
+ · simp [hh]
152
+
153
+ def hintGenerator (V : I → SecondQuestion Name) :
154
+ (F₂ × ((I → F₂) × (I → Module.Dual F₂ Triple))) →ₗ[F₂] Forms (SecondAlphabet V) where
155
+ toFun c := directHint V c.1 c.2.1 c.2.2
156
+ map_add' c d := by
157
+ ext a
158
+ change directHint V (c.1+d.1) (c.2.1+d.2.1) (c.2.2+d.2.2) a =
159
+ directHint V c.1 c.2.1 c.2.2 a + directHint V d.1 d.2.1 d.2.2 a
160
+ simp only [directHint_apply,Pi.add_apply,slotFunctional_add,LinearMap.add_apply,
161
+ Finset.sum_add_distrib]
162
+ abel
163
+ map_smul' k c := by
164
+ ext a
165
+ change directHint V (k • c.1) (k • c.2.1) (k • c.2.2) a =
166
+ k • (directHint V c.1 c.2.1 c.2.2 a)
167
+ simp only [directHint_apply,Pi.smul_apply,slotFunctional_smul,LinearMap.smul_apply,
168
+ ← Finset.smul_sum,← smul_add]
169
+
170
+ def unpackFunctional : (v : SecondQuestion Name) → Module.Dual F₂ (secondSlot v) →
171
+ F₂ × Module.Dual F₂ Triple
172
+ | .inl _, l => (l (fun _ => 1),0)
173
+ | .inr _, l => (0,l)
174
+
175
+ lemma oneSlotDual (l : Module.Dual F₂ (Fin 1 → F₂)) :
176
+ l (fun _ => 1) • (LinearMap.proj (0 : Fin 1)) = l := by
177
+ apply LinearMap.ext
178
+ intro a
179
+ have ha : a=a 0 • (fun _ : Fin 1 => (1 : F₂)) := by
180
+ funext p
181
+ fin_cases p
182
+ simp
183
+ change l (fun _ => 1)*a 0=l a
184
+ calc
185
+ _ = a 0 • l (fun _ => 1) := mul_comm _ _
186
+ _ = l (a 0 • (fun _ => 1)) := (l.map_smul _ _).symm
187
+ _ = l a := congrArg l ha.symm
188
+
189
+ lemma slotFunctional_unpack (v : SecondQuestion Name)
190
+ (l : Module.Dual F₂ (secondSlot v)) :
191
+ slotFunctional v (unpackFunctional v l).1 (unpackFunctional v l).2=l := by
192
+ cases v with
193
+ | inl x => exact oneSlotDual l
194
+ | inr E => rfl
195
+
196
+ lemma hintGenerator_surjective (V : I → SecondQuestion Name) :
197
+ Function.Surjective (hintGenerator V) := by
198
+ classical
199
+ intro f
200
+ let localPart (j : I) : Module.Dual F₂ (secondSlot (V j)) :=
201
+ f.linear.comp (LinearMap.single F₂ (fun j => secondSlot (V j)) j)
202
+ let c := fun j => unpackFunctional (V j) (localPart j)
203
+ refine ⟨(f 0,(fun j => (c j).1,fun j => (c j).2)),?_⟩
204
+ ext a
205
+ change directHint V (f 0) (fun j => (c j).1) (fun j => (c j).2) a=f a
206
+ rw [directHint_apply]
207
+ have hlin : (∑ j,slotFunctional (V j) (c j).1 (c j).2 (a j))=f.linear a := by
208
+ simp only [c,slotFunctional_unpack,localPart,LinearMap.comp_apply,LinearMap.single_apply]
209
+ rw [← map_sum,Finset.univ_sum_single]
210
+ rw [hlin]
211
+ simpa using (f.map_vadd (0 : SecondAlphabet V) a).symm
212
+
213
+ attribute [local instance] BinaryFourier.dualFintype
214
+
215
+ lemma uniform_hintGenerator (V : I → SecondQuestion Name) (f : Forms (SecondAlphabet V) → ℝ) :
216
+ (𝔼 c, f (hintGenerator V c)) = 𝔼 L, f L :=
217
+ IndependentSquares.expect_surjective_linear (hintGenerator V) (hintGenerator_surjective V) f
218
+
219
+ def hintTupleGenerator (V : I → SecondQuestion Name) (q : ℕ) :
220
+ (Fin q → (F₂ × ((I → F₂) × (I → Module.Dual F₂ Triple)))) →ₗ[F₂]
221
+ (Fin q → Forms (SecondAlphabet V)) :=
222
+ LinearMap.pi (fun k => (hintGenerator V).comp (LinearMap.proj k))
223
+
224
+ lemma hintTupleGenerator_surjective (V : I → SecondQuestion Name) (q : ℕ) :
225
+ Function.Surjective (hintTupleGenerator V q) := by
226
+ intro f
227
+ choose c hc using fun k => hintGenerator_surjective V (f k)
228
+ exact ⟨c,funext hc⟩
229
+
230
+ lemma uniform_hintTupleGenerator (V : I → SecondQuestion Name) (q : ℕ)
231
+ (f : (Fin q → Forms (SecondAlphabet V)) → ℝ) :
232
+ (𝔼 c, f (hintTupleGenerator V q c)) = 𝔼 L, f L :=
233
+ IndependentSquares.expect_surjective_linear (hintTupleGenerator V q)
234
+ (hintTupleGenerator_surjective V q) f
235
+
236
+ end MinUncut.Outer
237
+
238
+ end
239
+ namespace MinUncutGames.Foundations.Games
240
+
241
+ open scoped BigOperators
242
+
243
+ noncomputable section
244
+
245
+ structure FiniteDistribution (Ω : Type*) [Fintype Ω] where
246
+ weight : Ω → ℝ
247
+ nonnegative : ∀ x, 0 ≤ weight x
248
+ normalized : ∑ x, weight x = 1
249
+
250
+ namespace FiniteDistribution
251
+
252
+ variable {Ω Γ : Type*} [Fintype Ω] [Fintype Γ]
253
+
254
+ def expectation (μ : FiniteDistribution Ω) (f : Ω → ℝ) : ℝ :=
255
+ ∑ x, μ.weight x * f x
256
+
257
+ def probability (μ : FiniteDistribution Ω) (event : Ω → Bool) : ℝ :=
258
+ ∑ x, if event x then μ.weight x else 0
259
+
260
+ theorem probability_nonnegative (μ : FiniteDistribution Ω) (event : Ω → Bool) :
261
+ 0 ≤ μ.probability event := by
262
+ apply Finset.sum_nonneg
263
+ intro x _
264
+ split
265
+ · exact μ.nonnegative x
266
+ · exact le_rfl
267
+
268
+ theorem probability_le_one (μ : FiniteDistribution Ω) (event : Ω → Bool) :
269
+ μ.probability event ≤ 1 := by
270
+ rw [← μ.normalized]
271
+ apply Finset.sum_le_sum
272
+ intro x _
273
+ split
274
+ · exact le_rfl
275
+ · exact μ.nonnegative x
276
+
277
+ @[simp] theorem probability_true (μ : FiniteDistribution Ω) :
278
+ μ.probability (fun _ => true) = 1 := by
279
+ simpa [probability] using μ.normalized
280
+
281
+ @[simp] theorem probability_false (μ : FiniteDistribution Ω) :
282
+ μ.probability (fun _ => false) = 0 := by
283
+ simp [probability]
284
+
285
+ theorem probability_mono (μ : FiniteDistribution Ω) {event event' : Ω → Bool}
286
+ (h : ∀ x, event x = true → event' x = true) :
287
+ μ.probability event ≤ μ.probability event' := by
288
+ apply Finset.sum_le_sum
289
+ intro x _
290
+ by_cases hx : event x = true
291
+ · simp [hx, h x hx]
292
+ · simp [hx]
293
+ split
294
+ · exact μ.nonnegative x
295
+ · exact le_rfl
296
+
297
+ def pushforward (μ : FiniteDistribution Ω) (f : Ω → Γ) : FiniteDistribution Γ := by
298
+ classical
299
+ exact
300
+ { weight := fun y => ∑ x, if f x = y then μ.weight x else 0
301
+ nonnegative := fun y => Finset.sum_nonneg fun x _ => by
302
+ split
303
+ · exact μ.nonnegative x
304
+ · exact le_rfl
305
+ normalized := by
306
+ rw [Finset.sum_comm]
307
+ simpa using μ.normalized }
308
+
309
+ theorem probability_pushforward (μ : FiniteDistribution Ω) (f : Ω → Γ)
310
+ (event : Γ → Bool) :
311
+ (μ.pushforward f).probability event = μ.probability (fun x => event (f x)) := by
312
+ classical
313
+ simp only [probability, pushforward]
314
+ calc
315
+ _ = ∑ y, ∑ x, if f x = y then (if event y then μ.weight x else 0) else 0 := by
316
+ apply Finset.sum_congr rfl
317
+ intro y _
318
+ by_cases hy : event y = true <;> simp [hy]
319
+ _ = _ := by rw [Finset.sum_comm]; simp
320
+
321
+ def transport (μ : FiniteDistribution Ω) (equiv : Ω ≃ Γ) : FiniteDistribution Γ where
322
+ weight y := μ.weight (equiv.symm y)
323
+ nonnegative y := μ.nonnegative (equiv.symm y)
324
+ normalized := by rw [equiv.symm.sum_comp, μ.normalized]
325
+
326
+ theorem probability_transport (μ : FiniteDistribution Ω) (equiv : Ω ≃ Γ)
327
+ (event : Γ → Bool) :
328
+ (μ.transport equiv).probability event = μ.probability (fun x => event (equiv x)) := by
329
+ unfold probability transport
330
+ exact Fintype.sum_equiv equiv.symm _ _ (fun _ => by simp)
331
+
332
+ def iid (μ : FiniteDistribution Ω) (n : Nat) : FiniteDistribution (Fin n → Ω) where
333
+ weight x := ∏ i, μ.weight (x i)
334
+ nonnegative x := Finset.prod_nonneg fun i _ => μ.nonnegative (x i)
335
+ normalized := by rw [← Fintype.sum_pow, μ.normalized, one_pow]
336
+
337
+ theorem probability_iid_all (μ : FiniteDistribution Ω) (event : Ω → Bool) (n : Nat) :
338
+ (μ.iid n).probability (fun x => decide (∀ i, event (x i) = true)) =
339
+ μ.probability event ^ n := by
340
+ classical
341
+ unfold probability iid
342
+ rw [Fintype.sum_pow]
343
+ apply Finset.sum_congr rfl
344
+ intro x _
345
+ simp only [decide_eq_true_eq]
346
+ by_cases h : ∀ i, event (x i) = true
347
+ · simp [h]
348
+ · rw [ite_eq_right h]
349
+ obtain ⟨i, hi⟩ := not_forall.mp h
350
+ symm
351
+ apply Finset.prod_eq_zero (Finset.mem_univ i)
352
+ simp [hi]
353
+
354
+ end FiniteDistribution
355
+
356
+ abbrev Strategy (Q₁ Q₂ A₁ A₂ : Type*) := (Q₁ → A₁) × (Q₂ → A₂)
357
+
358
+ structure Game (Q₁ Q₂ A₁ A₂ : Type*) [Fintype Q₁] [Fintype Q₂]
359
+ [Fintype A₁] [Fintype A₂] where
360
+ questions : FiniteDistribution (Q₁ × Q₂)
361
+ accepts : Q₁ → Q₂ → A₁ → A₂ → Bool
362
+
363
+ namespace Game
364
+
365
+ variable {Q₁ Q₂ A₁ A₂ : Type*}
366
+ [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂]
367
+
368
+ def wins (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂)
369
+ (questions : Q₁ × Q₂) : Bool :=
370
+ G.accepts questions.1 questions.2 (strategy.1 questions.1) (strategy.2 questions.2)
371
+
372
+ def success (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) : ℝ :=
373
+ G.questions.probability (G.wins strategy)
374
+
375
+ theorem success_nonnegative (G : Game Q₁ Q₂ A₁ A₂)
376
+ (strategy : Strategy Q₁ Q₂ A₁ A₂) : 0 ≤ G.success strategy :=
377
+ G.questions.probability_nonnegative _
378
+
379
+ theorem success_le_one (G : Game Q₁ Q₂ A₁ A₂)
380
+ (strategy : Strategy Q₁ Q₂ A₁ A₂) : G.success strategy ≤ 1 :=
381
+ G.questions.probability_le_one _
382
+
383
+ def simulatedStrategy {R₁ R₂ B₁ B₂ : Type*}
384
+ (questionMap₁ : Q₁ → R₁) (questionMap₂ : Q₂ → R₂)
385
+ (answerMap₁ : Q₁ → B₁ → A₁) (answerMap₂ : Q₂ → B₂ → A₂)
386
+ (strategy : Strategy R₁ R₂ B₁ B₂) : Strategy Q₁ Q₂ A₁ A₂ :=
387
+ (fun x => answerMap₁ x (strategy.1 (questionMap₁ x)),
388
+ fun y => answerMap₂ y (strategy.2 (questionMap₂ y)))
389
+
390
+ theorem success_le_of_localSimulation {R₁ R₂ B₁ B₂ : Type*}
391
+ [Fintype R₁] [Fintype R₂] [Fintype B₁] [Fintype B₂]
392
+ (G : Game Q₁ Q₂ A₁ A₂) (H : Game R₁ R₂ B₁ B₂)
393
+ (questionMap₁ : Q₁ → R₁) (questionMap₂ : Q₂ → R₂)
394
+ (answerMap₁ : Q₁ → B₁ → A₁) (answerMap₂ : Q₂ → B₂ → A₂)
395
+ (questionLaw : H.questions =
396
+ G.questions.pushforward (fun q => (questionMap₁ q.1, questionMap₂ q.2)))
397
+ (acceptance : ∀ x y a b,
398
+ H.accepts (questionMap₁ x) (questionMap₂ y) a b = true →
399
+ G.accepts x y (answerMap₁ x a) (answerMap₂ y b) = true)
400
+ (strategy : Strategy R₁ R₂ B₁ B₂) :
401
+ H.success strategy ≤
402
+ G.success (simulatedStrategy questionMap₁ questionMap₂ answerMap₁ answerMap₂ strategy) := by
403
+ unfold success
404
+ rw [questionLaw, FiniteDistribution.probability_pushforward]
405
+ apply FiniteDistribution.probability_mono
406
+ intro questions h
407
+ exact acceptance questions.1 questions.2 _ _ h
408
+
409
+ def tupleQuestionEquiv (n : Nat) :
410
+ (Fin n → Q₁ × Q₂) ≃ (Fin n → Q₁) × (Fin n → Q₂) where
411
+ toFun questions := (fun i => (questions i).1, fun i => (questions i).2)
412
+ invFun questions := fun i => (questions.1 i, questions.2 i)
413
+ left_inv _ := rfl
414
+ right_inv _ := rfl
415
+
416
+ def repetition (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) :
417
+ Game (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂) := by
418
+ classical
419
+ exact
420
+ { questions := (G.questions.iid n).transport (tupleQuestionEquiv n)
421
+ accepts := fun x y a b => decide (∀ i, G.accepts (x i) (y i) (a i) (b i) = true) }
422
+
423
+ def repeatStrategy (strategy : Strategy Q₁ Q₂ A₁ A₂) (n : Nat) :
424
+ Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂) :=
425
+ (fun x i => strategy.1 (x i), fun y i => strategy.2 (y i))
426
+
427
+ theorem success_repeatStrategy (G : Game Q₁ Q₂ A₁ A₂)
428
+ (strategy : Strategy Q₁ Q₂ A₁ A₂) (n : Nat) :
429
+ (G.repetition n).success (repeatStrategy strategy n) = G.success strategy ^ n := by
430
+ unfold success
431
+ change ((G.questions.iid n).transport (tupleQuestionEquiv n)).probability _ = _
432
+ rw [FiniteDistribution.probability_transport]
433
+ exact G.questions.probability_iid_all (G.wins strategy) n
434
+
435
+ @[simp] theorem repetition_question_weight (G : Game Q₁ Q₂ A₁ A₂) (n : Nat)
436
+ (questions : (Fin n → Q₁) × (Fin n → Q₂)) :
437
+ (G.repetition n).questions.weight questions =
438
+ ∏ i, G.questions.weight (questions.1 i, questions.2 i) := rfl
439
+
440
+ @[simp] theorem repetition_accepts_iff (G : Game Q₁ Q₂ A₁ A₂) (n : Nat)
441
+ (x : Fin n → Q₁) (y : Fin n → Q₂) (a : Fin n → A₁) (b : Fin n → A₂) :
442
+ (G.repetition n).accepts x y a b = true ↔
443
+ ∀ i, G.accepts (x i) (y i) (a i) (b i) = true := by
444
+ classical
445
+ simp [repetition]
446
+
447
+ def coordinateWin (G : Game Q₁ Q₂ A₁ A₂) {n : Nat}
448
+ (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂))
449
+ (coordinate : Fin n) (questions : (Fin n → Q₁) × (Fin n → Q₂)) : Bool :=
450
+ G.accepts (questions.1 coordinate) (questions.2 coordinate)
451
+ (strategy.1 questions.1 coordinate) (strategy.2 questions.2 coordinate)
452
+
453
+ def selectedWins (G : Game Q₁ Q₂ A₁ A₂) {n : Nat}
454
+ (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂))
455
+ (selected : Finset (Fin n)) (questions : (Fin n → Q₁) × (Fin n → Q₂)) : Bool := by
456
+ classical
457
+ exact decide (∀ i ∈ selected, G.coordinateWin strategy i questions = true)
458
+
459
+ theorem selectedWins_mono (G : Game Q₁ Q₂ A₁ A₂) {n : Nat}
460
+ (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂))
461
+ {selected selected' : Finset (Fin n)} (h : selected ⊆ selected') :
462
+ (G.repetition n).questions.probability (G.selectedWins strategy selected') ≤
463
+ (G.repetition n).questions.probability (G.selectedWins strategy selected) := by
464
+ apply FiniteDistribution.probability_mono
465
+ intro questions hwin
466
+ simp only [selectedWins, decide_eq_true_eq] at hwin ⊢
467
+ intro i hi
468
+ exact hwin i (h hi)
469
+
470
+ @[simp] theorem selectedWins_empty (G : Game Q₁ Q₂ A₁ A₂) {n : Nat}
471
+ (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂))
472
+ (questions : (Fin n → Q₁) × (Fin n → Q₂)) :
473
+ G.selectedWins strategy ∅ questions = true := by
474
+ simp [selectedWins]
475
+
476
+ theorem selectedWins_univ (G : Game Q₁ Q₂ A₁ A₂) {n : Nat}
477
+ (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) :
478
+ G.selectedWins strategy Finset.univ = (G.repetition n).wins strategy := by
479
+ classical
480
+ funext questions
481
+ simp [selectedWins, coordinateWin, repetition, wins]
482
+
483
+ variable {Q₁ Q₂ A₁ A₂ : Type*}
484
+ [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂]
485
+ [Nonempty A₁] [Nonempty A₂]
486
+
487
+ def value (G : Game Q₁ Q₂ A₁ A₂) : ℝ := by
488
+ classical
489
+ exact Finset.univ.sup' Finset.univ_nonempty G.success
490
+
491
+ theorem success_le_value (G : Game Q₁ Q₂ A₁ A₂)
492
+ (strategy : Strategy Q₁ Q₂ A₁ A₂) : G.success strategy ≤ G.value := by
493
+ classical
494
+ exact Finset.le_sup' G.success (Finset.mem_univ strategy)
495
+
496
+ theorem value_le_iff (G : Game Q₁ Q₂ A₁ A₂) (bound : ℝ) :
497
+ G.value ≤ bound ↔ ∀ strategy : Strategy Q₁ Q₂ A₁ A₂, G.success strategy ≤ bound := by
498
+ classical
499
+ simp [value, Finset.sup'_le_iff]
500
+
501
+ theorem exists_optimal_strategy (G : Game Q₁ Q₂ A₁ A₂) :
502
+ ∃ strategy : Strategy Q₁ Q₂ A₁ A₂, G.success strategy = G.value := by
503
+ classical
504
+ obtain ⟨strategy, _, h⟩ := Finset.exists_mem_eq_sup'
505
+ (s := (Finset.univ : Finset (Strategy Q₁ Q₂ A₁ A₂))) Finset.univ_nonempty G.success
506
+ exact ⟨strategy, h.symm⟩
507
+
508
+ theorem value_nonnegative (G : Game Q₁ Q₂ A₁ A₂) : 0 ≤ G.value := by
509
+ obtain ⟨strategy, h⟩ := G.exists_optimal_strategy
510
+ rw [← h]
511
+ exact G.success_nonnegative strategy
512
+
513
+ theorem value_le_one (G : Game Q₁ Q₂ A₁ A₂) : G.value ≤ 1 :=
514
+ (G.value_le_iff 1).2 G.success_le_one
515
+
516
+ theorem randomized_success_le_value (G : Game Q₁ Q₂ A₁ A₂)
517
+ {Seed : Type*} [Fintype Seed] (seedLaw : FiniteDistribution Seed)
518
+ (strategies : Seed → Strategy Q₁ Q₂ A₁ A₂) :
519
+ seedLaw.expectation (fun seed => G.success (strategies seed)) ≤ G.value := by
520
+ unfold FiniteDistribution.expectation
521
+ calc
522
+ _ ≤ ∑ seed, seedLaw.weight seed * G.value := by
523
+ apply Finset.sum_le_sum
524
+ intro seed _
525
+ exact mul_le_mul_of_nonneg_left (G.success_le_value _) (seedLaw.nonnegative seed)
526
+ _ = G.value := by rw [← Finset.sum_mul, seedLaw.normalized, one_mul]
527
+
528
+ omit [Nonempty A₁] [Nonempty A₂] in
529
+ theorem success_repetition_zero (G : Game Q₁ Q₂ A₁ A₂)
530
+ (strategy : Strategy (Fin 0 → Q₁) (Fin 0 → Q₂) (Fin 0 → A₁) (Fin 0 → A₂)) :
531
+ (G.repetition 0).success strategy = 1 := by
532
+ have h : (G.repetition 0).wins strategy = fun _ => true := by
533
+ funext questions
534
+ simp [wins, repetition]
535
+ unfold success
536
+ rw [h, FiniteDistribution.probability_true]
537
+
538
+ @[simp] theorem value_repetition_zero (G : Game Q₁ Q₂ A₁ A₂) :
539
+ (G.repetition 0).value = 1 := by
540
+ obtain ⟨strategy, h⟩ := (G.repetition 0).exists_optimal_strategy
541
+ rw [← h]
542
+ exact G.success_repetition_zero strategy
543
+
544
+ theorem pow_value_le_repetition_value (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) :
545
+ G.value ^ n ≤ (G.repetition n).value := by
546
+ obtain ⟨strategy, h⟩ := G.exists_optimal_strategy
547
+ rw [← h, ← G.success_repeatStrategy strategy n]
548
+ exact (G.repetition n).success_le_value (repeatStrategy strategy n)
549
+
550
+ theorem value_le_of_localSimulation {R₁ R₂ B₁ B₂ : Type*}
551
+ [Fintype R₁] [Fintype R₂] [Fintype B₁] [Fintype B₂]
552
+ [Nonempty B₁] [Nonempty B₂]
553
+ (G : Game Q₁ Q₂ A₁ A₂) (H : Game R₁ R₂ B₁ B₂)
554
+ (questionMap₁ : Q₁ → R₁) (questionMap₂ : Q₂ → R₂)
555
+ (answerMap₁ : Q₁ → B₁ → A₁) (answerMap₂ : Q₂ → B₂ → A₂)
556
+ (questionLaw : H.questions =
557
+ G.questions.pushforward (fun q => (questionMap₁ q.1, questionMap₂ q.2)))
558
+ (acceptance : ∀ x y a b,
559
+ H.accepts (questionMap₁ x) (questionMap₂ y) a b = true →
560
+ G.accepts x y (answerMap₁ x a) (answerMap₂ y b) = true) :
561
+ H.value ≤ G.value := by
562
+ apply (H.value_le_iff _).2
563
+ intro strategy
564
+ exact (G.success_le_of_localSimulation H questionMap₁ questionMap₂
565
+ answerMap₁ answerMap₂ questionLaw acceptance strategy).trans (G.success_le_value _)
566
+
567
+ end Game
568
+
569
+ namespace FiniteDistribution
570
+ variable {Ω Γ Q A : Type*} [Fintype Ω] [Fintype Γ] [Fintype Q] [Fintype A]
571
+
572
+ theorem eq_of_weight_eq {μ ν : FiniteDistribution Ω}
573
+ (h : ∀ x, μ.weight x = ν.weight x) : μ = ν := by
574
+ cases μ with
575
+ | mk w hw hs =>
576
+ cases ν with
577
+ | mk w' hw' hs' =>
578
+ have he : w = w' := funext h
579
+ cases he
580
+ rfl
581
+
582
+ def table [DecidableEq Q] (responses : Q → FiniteDistribution A) :
583
+ FiniteDistribution (Q → A) := by
584
+ classical
585
+ exact
586
+ { weight := fun answers => ∏ q, (responses q).weight (answers q)
587
+ nonnegative := fun answers => Finset.prod_nonneg fun q _ =>
588
+ (responses q).nonnegative (answers q)
589
+ normalized := by
590
+ rw [← Fintype.prod_sum]
591
+ simp only [FiniteDistribution.normalized, Finset.prod_const_one] }
592
+
593
+ theorem expectation_table_eval [DecidableEq Q] (responses : Q → FiniteDistribution A)
594
+ (q₀ : Q) (h : A → ℝ) :
595
+ (table responses).expectation (fun answers => h (answers q₀)) =
596
+ (responses q₀).expectation h := by
597
+ classical
598
+ change (∑ answers : Q → A,
599
+ (∏ q, (responses q).weight (answers q)) * h (answers q₀)) =
600
+ ∑ a, (responses q₀).weight a * h a
601
+ calc
602
+ _ = ∑ answers : Q → A,
603
+ ∏ q, (responses q).weight (answers q) *
604
+ (if q = q₀ then h (answers q) else 1) := by
605
+ apply Finset.sum_congr rfl
606
+ intro answers _
607
+ rw [Finset.prod_mul_distrib]
608
+ simp
609
+ _ = ∏ q, ∑ a, (responses q).weight a * (if q = q₀ then h a else 1) :=
610
+ (Fintype.prod_sum (fun q a =>
611
+ (responses q).weight a * (if q = q₀ then h a else 1))).symm
612
+ _ = ∏ q : Q, if q = q₀ then (∑ a, (responses q₀).weight a * h a) else 1 := by
613
+ apply Finset.prod_congr rfl
614
+ intro q _
615
+ by_cases hq : q = q₀
616
+ · subst q
617
+ simp
618
+ · simp [hq, (responses q).normalized]
619
+ _ = _ := by simp
620
+
621
+ theorem table_eval_pushforward [DecidableEq Q]
622
+ (responses : Q → FiniteDistribution A) (q₀ : Q) :
623
+ (table responses).pushforward (fun answers => answers q₀) = responses q₀ := by
624
+ classical
625
+ apply eq_of_weight_eq
626
+ intro a
627
+ calc
628
+ _ = (table responses).expectation
629
+ (fun answers => if answers q₀ = a then 1 else 0) := by
630
+ simp [pushforward, expectation, mul_ite]
631
+ _ = (responses q₀).expectation (fun b => if b = a then 1 else 0) :=
632
+ expectation_table_eval responses q₀ (fun b => if b = a then (1 : ℝ) else 0)
633
+ _ = _ := by simp [expectation, mul_ite]
634
+
635
+ def product (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ) :
636
+ FiniteDistribution (Ω × Γ) where
637
+ weight x := μ.weight x.1 * ν.weight x.2
638
+ nonnegative x := mul_nonneg (μ.nonnegative _) (ν.nonnegative _)
639
+ normalized := by
640
+ rw [Fintype.sum_prod_type]
641
+ simp_rw [← Finset.mul_sum, ν.normalized, mul_one]
642
+ exact μ.normalized
643
+
644
+ theorem expectation_product (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ)
645
+ (f : Ω × Γ → ℝ) :
646
+ (μ.product ν).expectation f =
647
+ μ.expectation (fun x => ν.expectation (fun y => f (x,y))) := by
648
+ simp only [expectation, product, Fintype.sum_prod_type, Finset.mul_sum, mul_assoc]
649
+
650
+ theorem expectation_comm (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ)
651
+ (f : Ω → Γ → ℝ) :
652
+ μ.expectation (fun x => ν.expectation (f x)) =
653
+ ν.expectation (fun y => μ.expectation (fun x => f x y)) := by
654
+ unfold expectation
655
+ simp_rw [Finset.mul_sum]
656
+ rw [Finset.sum_comm]
657
+ apply Finset.sum_congr rfl
658
+ intro y _
659
+ apply Finset.sum_congr rfl
660
+ intro x _
661
+ exact mul_left_comm _ _ _
662
+
663
+ theorem expectation_congr (μ : FiniteDistribution Ω) {f g : Ω → ℝ}
664
+ (h : ∀ x, f x = g x) : μ.expectation f = μ.expectation g := by
665
+ unfold expectation
666
+ apply Finset.sum_congr rfl
667
+ intro x _
668
+ rw [h x]
669
+ end FiniteDistribution
670
+
671
+ namespace Game
672
+ variable {Q₁ Q₂ A₁ A₂ : Type*}
673
+ [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂]
674
+ [DecidableEq Q₁] [DecidableEq Q₂]
675
+
676
+ def responseTableLaw (responses₁ : Q₁ → FiniteDistribution A₁)
677
+ (responses₂ : Q₂ → FiniteDistribution A₂) :
678
+ FiniteDistribution (Strategy Q₁ Q₂ A₁ A₂) := by
679
+ classical
680
+ exact (FiniteDistribution.table responses₁).product (FiniteDistribution.table responses₂)
681
+
682
+ def stochasticSuccess (G : Game Q₁ Q₂ A₁ A₂)
683
+ (responses₁ : Q₁ → FiniteDistribution A₁)
684
+ (responses₂ : Q₂ → FiniteDistribution A₂) : ℝ :=
685
+ G.questions.expectation (fun q =>
686
+ (responses₁ q.1).expectation (fun a =>
687
+ (responses₂ q.2).expectation (fun b =>
688
+ if G.accepts q.1 q.2 a b then 1 else 0)))
689
+
690
+ omit [DecidableEq Q₁] [DecidableEq Q₂] in
691
+ theorem success_eq_question_expectation (G : Game Q₁ Q₂ A₁ A₂)
692
+ (strategy : Strategy Q₁ Q₂ A₁ A₂) :
693
+ G.success strategy = G.questions.expectation
694
+ (fun q => if G.wins strategy q then 1 else 0) := by
695
+ simp [success, FiniteDistribution.probability,
696
+ FiniteDistribution.expectation, mul_ite]
697
+
698
+ theorem table_success_eq_stochastic (G : Game Q₁ Q₂ A₁ A₂)
699
+ (responses₁ : Q₁ → FiniteDistribution A₁)
700
+ (responses₂ : Q₂ → FiniteDistribution A₂) :
701
+ (responseTableLaw responses₁ responses₂).expectation G.success =
702
+ G.stochasticSuccess responses₁ responses₂ := by
703
+ classical
704
+ unfold stochasticSuccess
705
+ calc
706
+ _ = (responseTableLaw responses₁ responses₂).expectation
707
+ (fun strategy => G.questions.expectation
708
+ (fun q => if G.wins strategy q then 1 else 0)) :=
709
+ FiniteDistribution.expectation_congr _ (G.success_eq_question_expectation)
710
+ _ = G.questions.expectation (fun q =>
711
+ (responseTableLaw responses₁ responses₂).expectation
712
+ (fun strategy => if G.wins strategy q then 1 else 0)) :=
713
+ FiniteDistribution.expectation_comm _ _ _
714
+ _ = _ := by
715
+ apply FiniteDistribution.expectation_congr
716
+ intro q
717
+ rw [responseTableLaw, FiniteDistribution.expectation_product]
718
+ change (FiniteDistribution.table responses₁).expectation
719
+ (fun answers₁ => (FiniteDistribution.table responses₂).expectation
720
+ (fun answers₂ =>
721
+ if G.accepts q.1 q.2 (answers₁ q.1) (answers₂ q.2) then 1 else 0)) = _
722
+ calc
723
+ _ = (FiniteDistribution.table responses₁).expectation
724
+ (fun answers₁ => (responses₂ q.2).expectation
725
+ (fun b => if G.accepts q.1 q.2 (answers₁ q.1) b then 1 else 0)) := by
726
+ apply FiniteDistribution.expectation_congr
727
+ intro answers₁
728
+ exact FiniteDistribution.expectation_table_eval responses₂ q.2
729
+ (fun b => if G.accepts q.1 q.2 (answers₁ q.1) b then (1 : ℝ) else 0)
730
+ _ = _ := FiniteDistribution.expectation_table_eval responses₁ q.1
731
+ (fun a => (responses₂ q.2).expectation
732
+ (fun b => if G.accepts q.1 q.2 a b then (1 : ℝ) else 0))
733
+
734
+ variable [Nonempty A₁] [Nonempty A₂]
735
+
736
+ theorem stochasticSuccess_le_value (G : Game Q₁ Q₂ A₁ A₂)
737
+ (responses₁ : Q₁ → FiniteDistribution A₁)
738
+ (responses₂ : Q₂ → FiniteDistribution A₂) :
739
+ G.stochasticSuccess responses₁ responses₂ ≤ G.value := by
740
+ classical
741
+ rw [← G.table_success_eq_stochastic]
742
+ exact G.randomized_success_le_value (responseTableLaw responses₁ responses₂) id
743
+
744
+ theorem exists_deterministic_ge_stochastic (G : Game Q₁ Q₂ A₁ A₂)
745
+ (responses₁ : Q₁ → FiniteDistribution A₁)
746
+ (responses₂ : Q₂ → FiniteDistribution A₂) :
747
+ ∃ strategy : Strategy Q₁ Q₂ A₁ A₂,
748
+ G.stochasticSuccess responses₁ responses₂ ≤ G.success strategy := by
749
+ obtain ⟨strategy, h⟩ := G.exists_optimal_strategy
750
+ refine ⟨strategy, ?_⟩
751
+ rw [h]
752
+ exact G.stochasticSuccess_le_value responses₁ responses₂
753
+ end Game
754
+ end
755
+ end MinUncutGames.Foundations.Games
756
+
757
+ end OAI
lean/OAI/Computability/MinUncut/Games/Parameters.lean ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.PCP.SelectionSequence
3
+ import OAI.Computability.MinUncut.PCP.Game
4
+
5
+ namespace OAI
6
+
7
+ section
8
+ namespace MinUncutGames.Integration.SourceParameters
9
+
10
+ def rate (gap : ℚ) : ℚ := 1 - gap ^ 3 / 100000
11
+
12
+ theorem rate_bounds {gap : ℚ} (hgap : 0 < gap) (hgap1 : gap ≤ 1) :
13
+ 0 < rate gap ∧ rate gap < 1 := by
14
+ have hcube : gap ^ 3 ≤ 1 := pow_le_one₀ hgap.le hgap1
15
+ have hcubePos : 0 < gap ^ 3 := pow_pos hgap _
16
+ constructor <;> unfold rate <;> linarith
17
+
18
+ theorem fourth_power_comparison {gap : ℚ} (hgap : 0 ≤ gap) (hgap1 : gap ≤ 1) :
19
+ 1 - (gap : ℝ) ^ 3 / 6000 ≤ (rate gap : ℝ) ^ 4 := by
20
+ have hg : (0 : ℝ) ≤ gap := by exact_mod_cast hgap
21
+ have hg1 : (gap : ℝ) ≤ 1 := by exact_mod_cast hgap1
22
+ have hc : (gap : ℝ) ^ 3 ≤ 1 := pow_le_one₀ hg hg1
23
+ have hc0 : 0 ≤ (gap : ℝ) ^ 3 := pow_nonneg hg _
24
+ have hb := one_add_mul_le_pow (a := -(gap : ℝ) ^ 3 / 100000)
25
+ (by linarith : (-2 : ℝ) ≤ -(gap : ℝ) ^ 3 / 100000) 4
26
+ have hr : (rate gap : ℝ) = 1 - (gap : ℝ) ^ 3 / 100000 := by
27
+ simp only [rate, Rat.cast_sub, Rat.cast_one, Rat.cast_div,
28
+ Rat.cast_pow, Rat.cast_ofNat]
29
+ rw [hr]
30
+ calc
31
+ _ ≤ 1 + 4 * (-(gap : ℝ) ^ 3 / 100000) := by linarith
32
+ _ ≤ _ := by simpa only [Nat.cast_ofNat, sub_eq_add_neg, neg_div] using hb
33
+
34
+ theorem four_bit_rate_comparison {gap : ℚ}
35
+ (hgap : 0 < gap) (hgap1 : gap ≤ 1) (n : Nat) :
36
+ (1 - (gap : ℝ) ^ 3 / 6000) ^ ((n : ℝ) / 4) ≤ (rate gap : ℝ) ^ n := by
37
+ have hg : (0 : ℝ) ≤ gap := by exact_mod_cast hgap.le
38
+ have hg1 : (gap : ℝ) ≤ 1 := by exact_mod_cast hgap1
39
+ have hc : (gap : ℝ) ^ 3 ≤ 1 := pow_le_one₀ hg hg1
40
+ have hr : (0 : ℝ) ≤ rate gap := by exact_mod_cast (rate_bounds hgap hgap1).1.le
41
+ calc
42
+ _ ≤ ((rate gap : ℝ) ^ 4) ^ ((n : ℝ) / 4) :=
43
+ Real.rpow_le_rpow (by linarith) (fourth_power_comparison hgap.le hgap1) (by positivity)
44
+ _ = (rate gap : ℝ) ^ ((4 : ℝ) * ((n : ℝ) / 4)) :=
45
+ (Real.rpow_natCast_mul hr 4 ((n : ℝ) / 4)).symm
46
+ _ = (rate gap : ℝ) ^ (n : ℝ) := by congr 1; ring
47
+ _ = _ := Real.rpow_natCast _ _
48
+
49
+ theorem logTwo_sixteen : MinUncutGames.Foundations.Repetition.logTwo 16 = 4 := by
50
+ unfold MinUncutGames.Foundations.Repetition.logTwo
51
+ rw [show (16 : ℝ) = 2 ^ 4 by norm_num, Real.log_pow]
52
+ have hlog : Real.log 2 ≠ 0 := ne_of_gt (Real.log_pos (by norm_num : (1 : ℝ) < 2))
53
+ simp [hlog]
54
+
55
+ theorem game_repetition_rate {Q₁ Q₂ A₁ A₂ : Type*}
56
+ [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂]
57
+ [Nonempty A₁] [Nonempty A₂] [DecidableEq Q₁] [DecidableEq Q₂]
58
+ (G : MinUncutGames.Foundations.Games.Game Q₁ Q₂ A₁ A₂)
59
+ {gap : ℚ} (hgap : 0 < gap) (hgap1 : gap ≤ 1)
60
+ (hcards : Fintype.card A₁ * Fintype.card A₂ = 16)
61
+ (hvalue : G.value ≤ 1 - (gap : ℝ)) (n : Nat) :
62
+ (G.repetition n).value ≤ (rate gap : ℝ) ^ n := by
63
+ have hg : (0 : ℝ) < gap := by exact_mod_cast hgap
64
+ have halphabet : MinUncutGames.Foundations.Repetition.logTwo
65
+ ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ 4 := by
66
+ rw [← Nat.cast_mul, hcards]
67
+ exact logTwo_sixteen.le
68
+ have h := MinUncutGames.Foundations.Repetition.holenstein_repetition_value
69
+ G n hvalue (by linarith) (by norm_num : (1 : ℝ) ≤ 4) halphabet
70
+ simp only [sub_sub_cancel] at h
71
+ exact h.trans (four_bit_rate_comparison hgap hgap1 n)
72
+
73
+ def sourceThreshold (D : Nat) (δ : ℚ) : ℚ := 4 * (D : ℚ)⁻¹ * δ ^ 2
74
+
75
+ theorem sourceThreshold_pos {D : Nat} (hD : 0 < D) {δ : ℚ} (hδ : 0 < δ) :
76
+ 0 < sourceThreshold D δ := by
77
+ unfold sourceThreshold
78
+ positivity
79
+
80
+ theorem exists_repetition_length {gap δ : ℚ} (hgap : 0 < gap) (hgap1 : gap ≤ 1)
81
+ (hδ : 0 < δ) {D : Nat} (hD : 0 < D) :
82
+ ∃ u : Nat, 0 < u ∧ (rate gap) ^ u < sourceThreshold D δ :=
83
+ MinUncutGames.Soundness.RepetitionUpper.exists_power_lt (rate gap) (sourceThreshold D δ)
84
+ (rate_bounds hgap hgap1).1.le (rate_bounds hgap hgap1).2 (sourceThreshold_pos hD hδ)
85
+
86
+ def repetitionLength (gap δ : ℚ) (hgap : 0 < gap) (hgap1 : gap ≤ 1)
87
+ (hδ : 0 < δ) (D : Nat) (hD : 0 < D) : Nat :=
88
+ Nat.find (exists_repetition_length hgap hgap1 hδ hD)
89
+
90
+ theorem repetitionLength_spec (gap δ : ℚ) (hgap : 0 < gap) (hgap1 : gap ≤ 1)
91
+ (hδ : 0 < δ) (D : Nat) (hD : 0 < D) :
92
+ 0 < repetitionLength gap δ hgap hgap1 hδ D hD ∧
93
+ rate gap ^ repetitionLength gap δ hgap hgap1 hδ D hD < sourceThreshold D δ :=
94
+ Nat.find_spec (exists_repetition_length hgap hgap1 hδ hD)
95
+
96
+ theorem repetitionLength_real_bound (gap δ : ℚ) (hgap : 0 < gap) (hgap1 : gap ≤ 1)
97
+ (hδ : 0 < δ) (D : Nat) (hD : 0 < D) :
98
+ (rate gap : ℝ) ^ repetitionLength gap δ hgap hgap1 hδ D hD ≤
99
+ 4 * (D : ℝ)⁻¹ * (δ : ℝ) ^ 2 := by
100
+ have h := (repetitionLength_spec gap δ hgap hgap1 hδ D hD).2.le
101
+ unfold sourceThreshold at h
102
+ have hr := (Rat.cast_le (K := ℝ)).mpr h
103
+ push_cast at hr
104
+ exact hr
105
+
106
+ end MinUncutGames.Integration.SourceParameters
107
+
108
+ end
109
+
110
+ end OAI
lean/OAI/Computability/MinUncut/Games/Pinsker.lean ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Games.Sampling
3
+
4
+ namespace OAI
5
+
6
+ namespace MinUncutGames.Foundations.Information
7
+
8
+ open scoped BigOperators
9
+
10
+ variable {α : Type*} [Fintype α]
11
+
12
+ noncomputable def hellingerSquared (p q : α → ℝ) : ℝ :=
13
+ ∑ a, (Real.sqrt (p a) - Real.sqrt (q a)) ^ 2
14
+
15
+ theorem sqrt_distance_le_relativeEntropy_term {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y)
16
+ (hs : x ≠ 0 → y ≠ 0) :
17
+ (Real.sqrt x - Real.sqrt y)^2 ≤ x * Real.log (x / y) - x + y := by
18
+ by_cases hxzero : x = 0
19
+ · subst x
20
+ simp [Real.sq_sqrt hy]
21
+ have hxpos : 0 < x := lt_of_le_of_ne hx (Ne.symm hxzero)
22
+ have hypos : 0 < y := lt_of_le_of_ne hy (Ne.symm (hs hxzero))
23
+ have hsx : 0 < Real.sqrt x := Real.sqrt_pos.2 hxpos
24
+ have hsy : 0 < Real.sqrt y := Real.sqrt_pos.2 hypos
25
+ have hlog := Real.log_le_sub_one_of_pos (div_pos hsy hsx)
26
+ have hlogid : Real.log (Real.sqrt y / Real.sqrt x) =
27
+ -(Real.log (x / y)) / 2 := by
28
+ rw [Real.log_div hsy.ne' hsx.ne', Real.log_sqrt hy, Real.log_sqrt hx,
29
+ Real.log_div hxzero (hs hxzero)]
30
+ ring
31
+ have hprod : x * (Real.sqrt y / Real.sqrt x) = Real.sqrt x * Real.sqrt y := by
32
+ calc
33
+ x * (Real.sqrt y / Real.sqrt x) = (Real.sqrt x)^2 * (Real.sqrt y / Real.sqrt x) := by
34
+ rw [Real.sq_sqrt hx]
35
+ _ = Real.sqrt x * Real.sqrt y := by field_simp [hsx.ne']
36
+ have hm := mul_le_mul_of_nonneg_left hlog hx
37
+ rw [hlogid, mul_sub, mul_one, hprod] at hm
38
+ nlinarith [Real.sq_sqrt hx, Real.sq_sqrt hy]
39
+
40
+ theorem hellingerSquared_le_relativeEntropy (p q : α → ℝ) (hp : IsProbability p)
41
+ (hq : IsProbability q) (hs : SupportedBy p q) :
42
+ hellingerSquared p q ≤ relativeEntropy p q := by
43
+ have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) =>
44
+ sqrt_distance_le_relativeEntropy_term (hp.1 a) (hq.1 a) (hs a))
45
+ simpa only [hellingerSquared, relativeEntropy, Finset.sum_add_distrib,
46
+ Finset.sum_sub_distrib, hp.2, hq.2, sub_add_cancel] using hsum
47
+
48
+ theorem totalVariation_sq_le_hellingerSquared (p q : α → ℝ) (hp : IsProbability p)
49
+ (hq : IsProbability q) : totalVariation p q ^ 2 ≤ hellingerSquared p q := by
50
+ have hfactor : ∀ a, |Real.sqrt (p a) - Real.sqrt (q a)| *
51
+ (Real.sqrt (p a) + Real.sqrt (q a)) = |p a - q a| := by
52
+ intro a
53
+ rw [← abs_of_nonneg (add_nonneg (Real.sqrt_nonneg _) (Real.sqrt_nonneg _)),
54
+ ← abs_mul]
55
+ congr 1
56
+ nlinarith [Real.sq_sqrt (hp.1 a), Real.sq_sqrt (hq.1 a)]
57
+ have hcs := Finset.sum_mul_sq_le_sq_mul_sq (Finset.univ : Finset α)
58
+ (fun a => |Real.sqrt (p a) - Real.sqrt (q a)|)
59
+ (fun a => Real.sqrt (p a) + Real.sqrt (q a))
60
+ simp only [hfactor, sq_abs] at hcs
61
+ have hpoint : ∀ a, (Real.sqrt (p a) + Real.sqrt (q a)) ^ 2 ≤ 2 * (p a + q a) := by
62
+ intro a
63
+ nlinarith [sq_nonneg (Real.sqrt (p a) - Real.sqrt (q a)),
64
+ Real.sq_sqrt (hp.1 a), Real.sq_sqrt (hq.1 a)]
65
+ have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => hpoint a)
66
+ simp only [← Finset.mul_sum, Finset.sum_add_distrib, hp.2, hq.2] at hsum
67
+ have hnonneg : 0 ≤ ∑ a, (Real.sqrt (p a) - Real.sqrt (q a)) ^ 2 :=
68
+ Finset.sum_nonneg (fun a _ => sq_nonneg _)
69
+ have hmul := mul_le_mul_of_nonneg_left hsum hnonneg
70
+ dsimp [totalVariation, hellingerSquared]
71
+ nlinarith
72
+
73
+ theorem totalVariation_sq_le_relativeEntropy (p q : α → ℝ) (hp : IsProbability p)
74
+ (hq : IsProbability q) (hs : SupportedBy p q) :
75
+ totalVariation p q ^ 2 ≤ relativeEntropy p q :=
76
+ (totalVariation_sq_le_hellingerSquared p q hp hq).trans
77
+ (hellingerSquared_le_relativeEntropy p q hp hq hs)
78
+
79
+ theorem posterior_totalVariation_sq_le_log (p w : α → ℝ) (hp : IsProbability p)
80
+ (hw : ∀ a, 0 ≤ w a) (hw_one : ∀ a, w a ≤ 1) {z : ℝ} (hz : 0 < z)
81
+ (hmass : ∑ a, p a * w a = z) :
82
+ totalVariation (posterior p w z) p ^ 2 ≤ Real.log (1 / z) := by
83
+ exact (totalVariation_sq_le_relativeEntropy _ _ (posterior_isProbability p w hp hw hz hmass)
84
+ hp (posterior_supportedBy p w z)).trans
85
+ (posterior_relativeEntropy_le p w hp hw hw_one hz hmass)
86
+
87
+ open scoped BigOperators
88
+
89
+ variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq ι]
90
+
91
+ noncomputable def coordinateMarginal (p : (ι → α) → ℝ) (i : ι) (a : α) : ℝ := by
92
+ classical
93
+ exact ∑ x, if x i = a then p x else 0
94
+
95
+ noncomputable def independentProduct (q : ι → α → ℝ) (x : ι → α) : ℝ := ∏ i, q i (x i)
96
+
97
+ theorem coordinateMarginal_isProbability (p : (ι → α) → ℝ) (hp : IsProbability p) (i : ι) :
98
+ IsProbability (coordinateMarginal p i) := by
99
+ classical
100
+ constructor
101
+ · intro a
102
+ apply Finset.sum_nonneg
103
+ intro x _
104
+ split_ifs
105
+ · exact hp.1 x
106
+ · exact le_rfl
107
+ · simp only [coordinateMarginal]
108
+ rw [Finset.sum_comm]
109
+ simpa using hp.2
110
+
111
+ theorem point_le_coordinateMarginal (p : (ι → α) → ℝ) (hp : IsProbability p)
112
+ (i : ι) (x : ι → α) : p x ≤ coordinateMarginal p i (x i) := by
113
+ classical
114
+ have h := Finset.single_le_sum
115
+ (f := fun y : ι → α => if y i = x i then p y else 0)
116
+ (fun y _ => by split_ifs; exact hp.1 y; exact le_rfl) (Finset.mem_univ x)
117
+ simpa [coordinateMarginal] using h
118
+
119
+ theorem marginal_expectation (p : (ι → α) → ℝ) (i : ι) (f : α → ℝ) :
120
+ (∑ x, p x * f (x i)) = ∑ a, coordinateMarginal p i a * f a := by
121
+ classical
122
+ simp only [coordinateMarginal, Finset.sum_mul]
123
+ rw [Finset.sum_comm]
124
+ apply Finset.sum_congr rfl
125
+ intro x _
126
+ simp [ite_mul]
127
+
128
+ theorem independentProduct_isProbability (q : ι → α → ℝ) (hq : ∀ i, IsProbability (q i)) :
129
+ IsProbability (independentProduct q) := by
130
+ classical
131
+ constructor
132
+ · intro x
133
+ exact Finset.prod_nonneg (fun i _ => (hq i).1 (x i))
134
+ · simp only [independentProduct, ← Fintype.prod_sum, (hq _).2, Finset.prod_const_one]
135
+
136
+ theorem joint_supportedBy_product_coordinateMarginals (p : (ι → α) → ℝ)
137
+ (hp : IsProbability p) : SupportedBy p (independentProduct (coordinateMarginal p)) := by
138
+ intro x hx
139
+ apply Finset.prod_ne_zero_iff.mpr
140
+ intro i _
141
+ exact ne_of_gt ((lt_of_le_of_ne (hp.1 x) (Ne.symm hx)).trans_le
142
+ (point_le_coordinateMarginal p hp i x))
143
+
144
+ theorem relativeEntropy_independent_reference (p : (ι → α) → ℝ) (q : ι → α → ℝ)
145
+ (hp : IsProbability p) (_hq : ∀ i, IsProbability (q i))
146
+ (hs : ∀ i, SupportedBy (coordinateMarginal p i) (q i)) :
147
+ relativeEntropy p (independentProduct q) =
148
+ relativeEntropy p (independentProduct (coordinateMarginal p)) +
149
+ ∑ i, relativeEntropy (coordinateMarginal p i) (q i) := by
150
+ classical
151
+ have hpoint : ∀ x : ι → α, p x * Real.log (p x / independentProduct q x) =
152
+ p x * Real.log (p x / independentProduct (coordinateMarginal p) x) +
153
+ ∑ i, p x * Real.log (coordinateMarginal p i (x i) / q i (x i)) := by
154
+ intro x
155
+ by_cases hx : p x = 0
156
+ · simp [hx]
157
+ have hm : ∀ i, coordinateMarginal p i (x i) ≠ 0 := by
158
+ intro i
159
+ exact ne_of_gt ((lt_of_le_of_ne (hp.1 x) (Ne.symm hx)).trans_le
160
+ (point_le_coordinateMarginal p hp i x))
161
+ have hqne : ∀ i, q i (x i) ≠ 0 := fun i => hs i (x i) (hm i)
162
+ have hmp : (∏ i, coordinateMarginal p i (x i)) ≠ 0 :=
163
+ Finset.prod_ne_zero_iff.mpr (fun i _ => hm i)
164
+ have hqp : (∏ i, q i (x i)) ≠ 0 :=
165
+ Finset.prod_ne_zero_iff.mpr (fun i _ => hqne i)
166
+ simp only [independentProduct, Real.log_div hx hmp, Real.log_div hx hqp,
167
+ Real.log_prod (fun i _ => hm i), Real.log_prod (fun i _ => hqne i)]
168
+ simp_rw [Real.log_div (hm _) (hqne _)]
169
+ rw [← Finset.mul_sum, Finset.sum_sub_distrib]
170
+ ring
171
+ calc
172
+ relativeEntropy p (independentProduct q) =
173
+ ∑ x, (p x * Real.log (p x / independentProduct (coordinateMarginal p) x) +
174
+ ∑ i, p x * Real.log (coordinateMarginal p i (x i) / q i (x i))) := by
175
+ exact Finset.sum_congr rfl (fun x _ => hpoint x)
176
+ _ = relativeEntropy p (independentProduct (coordinateMarginal p)) +
177
+ ∑ i, ∑ x, p x * Real.log (coordinateMarginal p i (x i) / q i (x i)) := by
178
+ rw [Finset.sum_add_distrib, Finset.sum_comm]
179
+ rfl
180
+ _ = relativeEntropy p (independentProduct (coordinateMarginal p)) +
181
+ ∑ i, relativeEntropy (coordinateMarginal p i) (q i) := by
182
+ congr 1
183
+ apply Finset.sum_congr rfl
184
+ intro i _
185
+ exact marginal_expectation p i (fun a => Real.log (coordinateMarginal p i a / q i a))
186
+
187
+ theorem coordinate_relativeEntropy_sum_le (p : (ι → α) → ℝ) (q : ι → α → ℝ)
188
+ (hp : IsProbability p) (hq : ∀ i, IsProbability (q i))
189
+ (hs : ∀ i, SupportedBy (coordinateMarginal p i) (q i)) :
190
+ (∑ i, relativeEntropy (coordinateMarginal p i) (q i)) ≤
191
+ relativeEntropy p (independentProduct q) := by
192
+ rw [relativeEntropy_independent_reference p q hp hq hs]
193
+ exact le_add_of_nonneg_left (relativeEntropy_nonneg _ _ hp
194
+ (independentProduct_isProbability _ (coordinateMarginal_isProbability p hp))
195
+ (joint_supportedBy_product_coordinateMarginals p hp))
196
+
197
+ theorem coordinate_totalVariation_sq_sum_le (p : (ι → α) → ℝ) (q : ι → α → ℝ)
198
+ (hp : IsProbability p) (hq : ∀ i, IsProbability (q i))
199
+ (hs : ∀ i, SupportedBy (coordinateMarginal p i) (q i)) :
200
+ (∑ i, totalVariation (coordinateMarginal p i) (q i) ^ 2) ≤
201
+ relativeEntropy p (independentProduct q) := by
202
+ exact (Finset.sum_le_sum (fun i _ => totalVariation_sq_le_relativeEntropy _ _
203
+ (coordinateMarginal_isProbability p hp i) (hq i) (hs i))).trans
204
+ (coordinate_relativeEntropy_sum_le p q hp hq hs)
205
+
206
+ theorem posterior_coordinate_supportedBy (q : ι → α → ℝ) (w : (ι → α) → ℝ)
207
+ (z : ℝ) (i : ι) :
208
+ SupportedBy (coordinateMarginal (posterior (independentProduct q) w z) i) (q i) := by
209
+ classical
210
+ intro a ha hqa
211
+ apply ha
212
+ unfold coordinateMarginal
213
+ apply Finset.sum_eq_zero
214
+ intro x _
215
+ by_cases hxa : x i = a
216
+ · have hzprod : independentProduct q x = 0 := by
217
+ exact Finset.prod_eq_zero (Finset.mem_univ i) (by simpa only [hxa] using hqa)
218
+ simp [hxa, posterior, hzprod]
219
+ · simp [hxa]
220
+
221
+ theorem posterior_coordinate_totalVariation_sq_sum_le_log
222
+ (q : ι → α → ℝ) (hq : ∀ i, IsProbability (q i)) (w : (ι → α) → ℝ)
223
+ (hw : ∀ x, 0 ≤ w x) (hw_one : ∀ x, w x ≤ 1) {z : ℝ} (hz : 0 < z)
224
+ (hmass : ∑ x, independentProduct q x * w x = z) :
225
+ (∑ i, totalVariation
226
+ (coordinateMarginal (posterior (independentProduct q) w z) i) (q i) ^ 2) ≤
227
+ Real.log (1 / z) := by
228
+ have hp := independentProduct_isProbability q hq
229
+ exact (coordinate_totalVariation_sq_sum_le _ q
230
+ (posterior_isProbability _ w hp hw hz hmass) hq
231
+ (posterior_coordinate_supportedBy q w z)).trans
232
+ (posterior_relativeEntropy_le _ w hp hw hw_one hz hmass)
233
+
234
+ theorem posterior_coordinate_totalVariation_sum_le_sqrt
235
+ (q : ι → α → ℝ) (hq : ∀ i, IsProbability (q i)) (w : (ι → α) → ℝ)
236
+ (hw : ∀ x, 0 ≤ w x) (hw_one : ∀ x, w x ≤ 1) {z : ℝ} (hz : 0 < z)
237
+ (hmass : ∑ x, independentProduct q x * w x = z) :
238
+ (∑ i, totalVariation
239
+ (coordinateMarginal (posterior (independentProduct q) w z) i) (q i)) ≤
240
+ Real.sqrt ((Fintype.card ι : ℝ) * Real.log (1 / z)) := by
241
+ let d : ι → ℝ := fun i => totalVariation
242
+ (coordinateMarginal (posterior (independentProduct q) w z) i) (q i)
243
+ have hsq := posterior_coordinate_totalVariation_sq_sum_le_log q hq w hw hw_one hz hmass
244
+ have hcs := Finset.sum_mul_sq_le_sq_mul_sq (Finset.univ : Finset ι) d (fun _ => (1 : ℝ))
245
+ simp only [mul_one, one_pow, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_one] at hcs
246
+ have hln : 0 ≤ Real.log (1 / z) := by
247
+ have hp := independentProduct_isProbability q hq
248
+ exact (relativeEntropy_nonneg _ _ (posterior_isProbability _ w hp hw hz hmass) hp
249
+ (posterior_supportedBy _ w z)).trans
250
+ (posterior_relativeEntropy_le _ w hp hw hw_one hz hmass)
251
+ have hcard : 0 ≤ (Fintype.card ι : ℝ) := Nat.cast_nonneg _
252
+ have hmul := mul_le_mul_of_nonneg_left hsq hcard
253
+ have hsqrt := Real.sq_sqrt (mul_nonneg hcard hln)
254
+ have hsqrtpos := Real.sqrt_nonneg ((Fintype.card ι : ℝ) * Real.log (1 / z))
255
+ change (∑ i, d i) ≤ _
256
+ change (∑ i, d i ^ 2) ≤ _ at hsq
257
+ change (Fintype.card ι : ℝ) * (∑ i, d i ^ 2) ≤ _ at hmul
258
+ nlinarith
259
+
260
+ theorem posterior_coordinate_totalVariation_sq_sum_le_binaryLog
261
+ (q : ι → α → ℝ) (hq : ∀ i, IsProbability (q i)) (w : (ι → α) → ℝ)
262
+ (hw : ∀ x, 0 ≤ w x) (hw_one : ∀ x, w x ≤ 1) {z : ℝ} (hz : 0 < z)
263
+ (hmass : ∑ x, independentProduct q x * w x = z) :
264
+ (∑ i, totalVariation
265
+ (coordinateMarginal (posterior (independentProduct q) w z) i) (q i) ^ 2) ≤
266
+ Real.log (1 / z) / Real.log 2 := by
267
+ exact le_binaryLog_of_le_log (Finset.sum_nonneg (fun _ _ => sq_nonneg _))
268
+ (posterior_coordinate_totalVariation_sq_sum_le_log q hq w hw hw_one hz hmass)
269
+
270
+ open scoped BigOperators
271
+
272
+ variable {α : Type*} [Fintype α]
273
+
274
+ theorem normalize_isProbability (b : α → ℝ) (hb : ∀ a, 0 ≤ b a)
275
+ {B : ℝ} (hB : 0 < B) (hmass : ∑ a, b a = B) :
276
+ IsProbability (fun a => b a / B) := by
277
+ constructor
278
+ · intro a
279
+ exact div_nonneg (hb a) hB.le
280
+ · simp only [div_eq_mul_inv, ← Finset.sum_mul, hmass, mul_inv_cancel₀ hB.ne']
281
+
282
+ theorem relativeEntropy_normalize_right (p b : α → ℝ) (hp : IsProbability p)
283
+ (hs : SupportedBy p b) {B : ℝ} (hB : 0 < B) :
284
+ relativeEntropy p (fun a => b a / B) = relativeEntropy p b + Real.log B := by
285
+ have hpoint : ∀ a, p a * Real.log (p a / (b a / B)) =
286
+ p a * Real.log (p a / b a) + p a * Real.log B := by
287
+ intro a
288
+ by_cases hpa : p a = 0
289
+ · simp [hpa]
290
+ have hbne := hs a hpa
291
+ rw [Real.log_div hpa (div_ne_zero hbne hB.ne'), Real.log_div hbne hB.ne',
292
+ Real.log_div hpa hbne]
293
+ ring
294
+ simp only [relativeEntropy, hpoint, Finset.sum_add_distrib, ← Finset.sum_mul, hp.2, one_mul]
295
+
296
+ theorem neg_relativeEntropy_le_log_mass (p b : α → ℝ) (hp : IsProbability p)
297
+ (hb : ∀ a, 0 ≤ b a) (hs : SupportedBy p b) {B : ℝ} (hB : 0 < B)
298
+ (hmass : ∑ a, b a = B) : -relativeEntropy p b ≤ Real.log B := by
299
+ have hs' : SupportedBy p (fun a => b a / B) :=
300
+ fun a ha => div_ne_zero (hs a ha) hB.ne'
301
+ have hnonneg := relativeEntropy_nonneg p (fun a => b a / B) hp
302
+ (normalize_isProbability b hb hB hmass) hs'
303
+ rw [relativeEntropy_normalize_right p b hp hs hB] at hnonneg
304
+ linarith
305
+
306
+ theorem posterior_weighted_log_inverse_le (p b c : α → ℝ) (hp : IsProbability p)
307
+ (hb : ∀ a, 0 ≤ b a) {z B : ℝ} (hz : 0 < z) (hB : 0 < B)
308
+ (hmass : ∑ a, b a = B) (hpost : ∀ a, p a = b a * c a / z) :
309
+ (∑ a, p a * Real.log (1 / c a)) ≤ Real.log (B / z) := by
310
+ have hs : SupportedBy p b := by
311
+ intro a ha hba
312
+ apply ha
313
+ rw [hpost, hba, zero_mul, zero_div]
314
+ have hpoint : ∀ a, p a * Real.log (1 / c a) =
315
+ p a * Real.log (1 / z) - p a * Real.log (p a / b a) := by
316
+ intro a
317
+ by_cases hpa : p a = 0
318
+ · simp [hpa]
319
+ have hbne := hs a hpa
320
+ have hcne : c a ≠ 0 := by
321
+ intro hca
322
+ apply hpa
323
+ rw [hpost, hca, mul_zero, zero_div]
324
+ have hratio : p a / b a = c a / z := by
325
+ rw [hpost]
326
+ field_simp [hbne, hz.ne']
327
+ rw [hratio, Real.log_div hcne hz.ne', Real.log_div one_ne_zero hcne,
328
+ Real.log_div one_ne_zero hz.ne', Real.log_one]
329
+ ring
330
+ have hid : (∑ a, p a * Real.log (1 / c a)) =
331
+ Real.log (1 / z) - relativeEntropy p b := by
332
+ simp only [hpoint, Finset.sum_sub_distrib, ← Finset.sum_mul, hp.2, one_mul,
333
+ relativeEntropy]
334
+ have hkl := neg_relativeEntropy_le_log_mass p b hp hb hs hB hmass
335
+ rw [hid, Real.log_div hB.ne' hz.ne', Real.log_div one_ne_zero hz.ne', Real.log_one]
336
+ linarith
337
+
338
+ open scoped BigOperators
339
+
340
+ noncomputable def posteriorOrOriginal
341
+ {A : Type*} [Fintype A] (p e : A → ℝ) (z : ℝ) : A → ℝ := by
342
+ classical
343
+ exact if 0 < z then posterior p e z else p
344
+
345
+ theorem posteriorOrOriginal_isProbability
346
+ {A : Type*} [Fintype A] (p e : A → ℝ)
347
+ (hp : IsProbability p) (he : ∀ a, 0 ≤ e a)
348
+ {z : ℝ} (hmass : ∑ a, p a * e a = z) :
349
+ IsProbability (posteriorOrOriginal p e z) := by
350
+ classical
351
+ by_cases hz : 0 < z
352
+ · simpa only [posteriorOrOriginal, ite_eq_left hz] using
353
+ posterior_isProbability p e hp he hz hmass
354
+ · simpa only [posteriorOrOriginal, ite_eq_right hz] using hp
355
+
356
+ theorem mass_mul_posteriorOrOriginal
357
+ {A : Type*} [Fintype A] (p e : A → ℝ)
358
+ (hp : IsProbability p) (he : ∀ a, 0 ≤ e a)
359
+ {c : ℝ} (hmass : ∑ a, p a * e a = c) (x : A) :
360
+ c * posteriorOrOriginal p e c x = p x * e x := by
361
+ classical
362
+ by_cases hc : 0 < c
363
+ · simp only [posteriorOrOriginal, ite_eq_left hc, posterior]
364
+ field_simp [hc.ne']
365
+ · have hcnonneg : 0 ≤ c := by
366
+ rw [← hmass]
367
+ exact Finset.sum_nonneg (fun a _ => mul_nonneg (hp.1 a) (he a))
368
+ have hc0 : c = 0 := le_antisymm (le_of_not_gt hc) hcnonneg
369
+ have hpoint := Finset.single_le_sum
370
+ (fun a (_ : a ∈ (Finset.univ : Finset A)) => mul_nonneg (hp.1 a) (he a))
371
+ (Finset.mem_univ x)
372
+ rw [hmass, hc0] at hpoint
373
+ have hzero : p x * e x = 0 := le_antisymm hpoint (mul_nonneg (hp.1 x) (he x))
374
+ simp [posteriorOrOriginal, hc0, hzero]
375
+
376
+ theorem weighted_coordinate_posterior_recombine
377
+ {I A : Type*} [Fintype I] [Fintype A] [DecidableEq I] [DecidableEq A]
378
+ (p e : (I → A) → ℝ) (hp : IsProbability p) (he : ∀ x, 0 ≤ e x)
379
+ {c : ℝ} (hmass : ∑ x, p x * e x = c) (b z : ℝ) (i : I) (a : A) :
380
+ (b * c / z) * coordinateMarginal (posteriorOrOriginal p e c) i a =
381
+ (b / z) * ∑ x, if x i = a then p x * e x else 0 := by
382
+ classical
383
+ simp only [coordinateMarginal, Finset.mul_sum]
384
+ apply Finset.sum_congr rfl
385
+ intro x _
386
+ by_cases hxa : x i = a
387
+ · simp only [ite_eq_left hxa]
388
+ calc
389
+ (b * c / z) * posteriorOrOriginal p e c x =
390
+ (b / z) * (c * posteriorOrOriginal p e c x) := by ring
391
+ _ = (b / z) * (p x * e x) := by
392
+ rw [mass_mul_posteriorOrOriginal p e hp he hmass x]
393
+ · simp [hxa]
394
+
395
+ variable {J I A : Type*}
396
+ variable [Fintype J] [Fintype I] [Fintype A] [DecidableEq I]
397
+
398
+ theorem side_information_bound
399
+ (w b c : J → ℝ)
400
+ (q : J → I → A → ℝ)
401
+ (e : J → (I → A) → ℝ)
402
+ (hw : IsProbability w)
403
+ (hb : ∀ j, 0 ≤ b j)
404
+ (hq : ∀ j i, IsProbability (q j i))
405
+ (he : ∀ j x, 0 ≤ e j x)
406
+ (he_one : ∀ j x, e j x ≤ 1)
407
+ (hmass : ∀ j, ∑ x, independentProduct (q j) x * e j x = c j)
408
+ {z B : ℝ} (hz : 0 < z) (hB : 0 < B)
409
+ (hbase : ∑ j, b j = B)
410
+ (hweight : ∀ j, w j = b j * c j / z) :
411
+ (∑ i, totalVariation
412
+ (fun ja : J × A => w ja.1 * coordinateMarginal
413
+ (posteriorOrOriginal (independentProduct (q ja.1))
414
+ (e ja.1) (c ja.1)) i ja.2)
415
+ (fun ja : J × A => w ja.1 * q ja.1 i ja.2)) ≤
416
+ Real.sqrt ((Fintype.card I : ℝ) * Real.log (B / z)) := by
417
+ classical
418
+ let d : J → I → ℝ := fun j i => totalVariation
419
+ (coordinateMarginal
420
+ (posteriorOrOriginal (independentProduct (q j)) (e j) (c j)) i)
421
+ (q j i)
422
+ have hbudget : ∀ j,
423
+ w j * (∑ i, d j i ^ 2) ≤ w j * Real.log (1 / c j) := by
424
+ intro j
425
+ by_cases hwzero : w j = 0
426
+ · simp [hwzero]
427
+ have hcne : c j ≠ 0 := by
428
+ intro hczero
429
+ apply hwzero
430
+ rw [hweight j, hczero, mul_zero, zero_div]
431
+ have hcnonneg : 0 ≤ c j := by
432
+ rw [← hmass j]
433
+ exact Finset.sum_nonneg (fun x _ => mul_nonneg
434
+ ((independentProduct_isProbability (q j) (hq j)).1 x) (he j x))
435
+ have hcpos : 0 < c j := lt_of_le_of_ne hcnonneg (Ne.symm hcne)
436
+ have hlocal := posterior_coordinate_totalVariation_sq_sum_le_log
437
+ (q j) (hq j) (e j) (he j) (he_one j) hcpos (hmass j)
438
+ have hweighted := mul_le_mul_of_nonneg_left hlocal (hw.1 j)
439
+ simpa only [d, posteriorOrOriginal, ite_eq_left hcpos] using hweighted
440
+ have hcs := weighted_coordinate_sum_sq_le
441
+ w d (fun j => Real.log (1 / c j)) hw hbudget
442
+ have hlog := posterior_weighted_log_inverse_le w b c hw hb hz hB hbase hweight
443
+ have hsq : (∑ i, ∑ j, w j * d j i)^2 ≤
444
+ (Fintype.card I : ℝ) * Real.log (B / z) :=
445
+ hcs.trans (mul_le_mul_of_nonneg_left hlog (Nat.cast_nonneg _))
446
+ have htv : ∀ i, totalVariation
447
+ (fun ja : J × A => w ja.1 * coordinateMarginal
448
+ (posteriorOrOriginal (independentProduct (q ja.1))
449
+ (e ja.1) (c ja.1)) i ja.2)
450
+ (fun ja : J × A => w ja.1 * q ja.1 i ja.2) =
451
+ ∑ j, w j * d j i := by
452
+ intro i
453
+ exact totalVariation_joint_common_weights w
454
+ (fun j => coordinateMarginal
455
+ (posteriorOrOriginal (independentProduct (q j)) (e j) (c j)) i)
456
+ (fun j => q j i) hw.1
457
+ simp_rw [htv]
458
+ have hradicand : 0 ≤ (Fintype.card I : ℝ) * Real.log (B / z) :=
459
+ (sq_nonneg _).trans hsq
460
+ have hsqrt := Real.sq_sqrt hradicand
461
+ have hsqrt_nonneg := Real.sqrt_nonneg ((Fintype.card I : ℝ) * Real.log (B / z))
462
+ nlinarith
463
+
464
+ variable {T V : Type*} [Fintype T] [Fintype V] [Nonempty V]
465
+
466
+ theorem finite_side_information_bound
467
+ (pT : T → ℝ) (q : T → I → A → ℝ)
468
+ (e : T × V → (I → A) → ℝ) (c w : T × V → ℝ)
469
+ (hpT : IsProbability pT)
470
+ (hq : ∀ t i, IsProbability (q t i))
471
+ (he : ∀ tv x, 0 ≤ e tv x)
472
+ (he_sum : ∀ t x, (∑ v, e (t, v) x) ≤ 1)
473
+ (hc : ∀ tv, ∑ x, independentProduct (q tv.1) x * e tv x = c tv)
474
+ {z : ℝ} (hz : 0 < z)
475
+ (hZ : ∑ tv, pT tv.1 * c tv = z)
476
+ (hweight : ∀ tv, w tv = pT tv.1 * c tv / z) :
477
+ (∑ i, totalVariation
478
+ (fun tva : (T × V) × A => w tva.1 * coordinateMarginal
479
+ (posteriorOrOriginal (independentProduct (q tva.1.1))
480
+ (e tva.1) (c tva.1)) i tva.2)
481
+ (fun tva : (T × V) × A => w tva.1 * q tva.1.1 i tva.2)) ≤
482
+ Real.sqrt ((Fintype.card I : ℝ) *
483
+ (Real.log (Fintype.card V : ℝ) + Real.log (1 / z))) := by
484
+ classical
485
+ have hcnonneg : ∀ tv, 0 ≤ c tv := by
486
+ intro tv
487
+ rw [← hc tv]
488
+ exact Finset.sum_nonneg (fun x _ => mul_nonneg
489
+ ((independentProduct_isProbability (q tv.1) (hq tv.1)).1 x) (he tv x))
490
+ have hw : IsProbability w := by
491
+ constructor
492
+ · intro tv
493
+ rw [hweight tv]
494
+ exact div_nonneg (mul_nonneg (hpT.1 tv.1) (hcnonneg tv)) hz.le
495
+ · simp_rw [hweight, div_eq_mul_inv]
496
+ rw [← Finset.sum_mul, hZ, mul_inv_cancel₀ hz.ne']
497
+ have he_one : ∀ tv x, e tv x ≤ 1 := by
498
+ intro tv x
499
+ have hsingle : e tv x ≤ ∑ v, e (tv.1, v) x :=
500
+ Finset.single_le_sum (fun v _ => he (tv.1, v) x) (Finset.mem_univ tv.2)
501
+ exact hsingle.trans (he_sum tv.1 x)
502
+ have hB : 0 < (Fintype.card V : ℝ) := Nat.cast_pos.mpr Fintype.card_pos
503
+ have hbase : (∑ tv : T × V, pT tv.1) = (Fintype.card V : ℝ) := by
504
+ simp only [Fintype.sum_prod_type, Finset.sum_const, Finset.card_univ,
505
+ nsmul_eq_mul, ← Finset.mul_sum, hpT.2, mul_one]
506
+ have h := side_information_bound w (fun tv : T × V => pT tv.1) c
507
+ (fun tv => q tv.1) e hw (fun tv => hpT.1 tv.1) (fun tv => hq tv.1)
508
+ he he_one hc hz hB hbase hweight
509
+ have hlog : Real.log ((Fintype.card V : ℝ) / z) =
510
+ Real.log (Fintype.card V : ℝ) + Real.log (1 / z) := by
511
+ rw [Real.log_div hB.ne' hz.ne', Real.log_div one_ne_zero hz.ne', Real.log_one]
512
+ ring
513
+ simpa only [hlog] using h
514
+
515
+ end MinUncutGames.Foundations.Information
516
+
517
+ end OAI
lean/OAI/Computability/MinUncut/Games/PoweringGlobalEnumeration.lean ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+ import OAI.Computability.MinUncut.Machines.PoweringMachineRotor
3
+
4
+ namespace OAI
5
+
6
+ section
7
+ namespace MinUncutGames.Foundations.Complexity.PoweringGlobalEnumeration
8
+
9
+ open PoweringMachineLoop PoweringMachineInitialize
10
+
11
+ def headerTapeEquiv : HeaderTape ≃ Fin 4 where
12
+ toFun
13
+ | .source => 0
14
+ | .counter => 1
15
+ | .vertices => 2
16
+ | .darts => 3
17
+ invFun i := if i = 0 then .source else if i = 1 then .counter
18
+ else if i = 2 then .vertices else .darts
19
+ left_inv tape := by cases tape <;> rfl
20
+ right_inv i := by fin_cases i <;> rfl
21
+
22
+ def unitTapeEquiv : Unit ≃ Fin 1 where
23
+ toFun _ := 0
24
+ invFun _ := ()
25
+ left_inv u := by cases u; rfl
26
+ right_inv i := (Fin.eq_zero i).symm
27
+
28
+ def sharedTapeEquiv (max : Nat) : PoweringMachineTapes.Tape max ≃ Fin (11 + max) :=
29
+ finSumFinEquiv
30
+
31
+ def extraTapeEquiv (max : Nat) : ExtraTape max ≃ Fin (11 + max + 1) :=
32
+ (Equiv.sumCongr (sharedTapeEquiv max) unitTapeEquiv).trans finSumFinEquiv
33
+
34
+ def globalTapeEquiv (max : Nat) : GlobalTape max ≃ Fin (4 + (11 + max + 1)) :=
35
+ (Equiv.sumCongr headerTapeEquiv (extraTapeEquiv max)).trans finSumFinEquiv
36
+
37
+ def enumeration (max : Nat) : Fin (4 + (11 + max + 1)) ≃ GlobalTape max :=
38
+ (globalTapeEquiv max).symm
39
+
40
+ @[simp] theorem globalTapeEquiv_enumeration (max : Nat) (i : Fin (4 + (11 + max + 1))) :
41
+ globalTapeEquiv max (enumeration max i) = i :=
42
+ (globalTapeEquiv max).apply_symm_apply i
43
+
44
+ @[simp] theorem enumeration_globalTapeEquiv (max : Nat) (tape : GlobalTape max) :
45
+ enumeration max (globalTapeEquiv max tape) = tape :=
46
+ (globalTapeEquiv max).symm_apply_apply tape
47
+
48
+ @[simp] theorem source_index (max : Nat) :
49
+ (globalTapeEquiv max (.inl .source)).val = 0 := rfl
50
+
51
+ @[simp] theorem counter_index (max : Nat) :
52
+ (globalTapeEquiv max (.inl .counter)).val = 1 := rfl
53
+
54
+ @[simp] theorem vertices_index (max : Nat) :
55
+ (globalTapeEquiv max (.inl .vertices)).val = 2 := rfl
56
+
57
+ @[simp] theorem darts_index (max : Nat) :
58
+ (globalTapeEquiv max (.inl .darts)).val = 3 := rfl
59
+
60
+ theorem sharedRole_index (max : Nat) (i : Fin 11) :
61
+ (globalTapeEquiv max (.inr (.inl (.inl i)))).val = 4 + i.val := rfl
62
+
63
+ theorem trajectory_index (max : Nat) (i : Fin max) :
64
+ (globalTapeEquiv max (.inr (.inl (.inr i)))).val = 4 + (11 + i.val) := rfl
65
+
66
+ @[simp] theorem finalOutput_index (max : Nat) :
67
+ (globalTapeEquiv max (finalOutput max)).val = 4 + (11 + max) := rfl
68
+
69
+ theorem card_globalTape (max : Nat) :
70
+ Fintype.card (GlobalTape max) = 4 + (11 + max + 1) := by
71
+ simpa only [Fintype.card_fin] using Fintype.card_congr (globalTapeEquiv max)
72
+
73
+ theorem natCard_globalTape (max : Nat) :
74
+ Nat.card (GlobalTape max) = 4 + (11 + max + 1) := by
75
+ simpa only [Nat.card_fin] using Nat.card_congr (globalTapeEquiv max)
76
+
77
+ def allTapes (max : Nat) : List (GlobalTape max) := List.ofFn (enumeration max)
78
+
79
+ theorem allTapes_length (max : Nat) : (allTapes max).length = 4 + (11 + max + 1) := by
80
+ simpa only [allTapes] using (List.length_ofFn (f := enumeration max))
81
+
82
+ theorem mem_allTapes (max : Nat) (tape : GlobalTape max) : tape ∈ allTapes max := by
83
+ change tape ∈ List.ofFn (enumeration max)
84
+ apply List.mem_ofFn.mpr
85
+ exact ⟨globalTapeEquiv max tape, enumeration_globalTapeEquiv max tape⟩
86
+
87
+ end MinUncutGames.Foundations.Complexity.PoweringGlobalEnumeration
88
+
89
+ end
90
+
91
+ end OAI