Add lean source and binary files (part 62)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lean/OAI/Computability/MinUncut/Estimates/RowListBridge.leanAdded+63
- lean/OAI/Computability/MinUncut/Estimates/SamplerAssembly.leanAdded+93
- lean/OAI/Computability/MinUncut/Estimates/SamplerCost.leanAdded+106
- lean/OAI/Computability/MinUncut/Estimates/SecondFailureIndicator.leanAdded+259
- lean/OAI/Computability/MinUncut/Estimates/SelectedProject.leanAdded+59
- lean/OAI/Computability/MinUncut/Estimates/SelectedProjectSliceContinuous.leanAdded+53
- lean/OAI/Computability/MinUncut/Estimates/SelectedSyntax.leanAdded+57
- lean/OAI/Computability/MinUncut/Estimates/SingleRow.leanAdded+125
- lean/OAI/Computability/MinUncut/Estimates/TM2Costed.leanAdded+724
- lean/OAI/Computability/MinUncut/Estimates/TableLawPacking.leanAdded+92
- lean/OAI/Computability/MinUncut/Estimates/TableTestFunctions.leanAdded+101
- lean/OAI/Computability/MinUncut/Estimates/TemplateExpressions.leanAdded+376
- lean/OAI/Computability/MinUncut/Estimates/UniformAlgebra.leanAdded+90
- lean/OAI/Computability/MinUncut/Estimates/UniformBoolean.leanAdded+97
- lean/OAI/Computability/MinUncut/Estimates/UniformEquation.leanAdded+288
- lean/OAI/Computability/MinUncut/Estimates/UniformEquationOutput.leanAdded+298
- lean/OAI/Computability/MinUncut/Estimates/UniformFaceArray.leanAdded+36
- lean/OAI/Computability/MinUncut/Estimates/UniformGrid.leanAdded+483
- lean/OAI/Computability/MinUncut/Estimates/UniformOutput.leanAdded+27
- lean/OAI/Computability/MinUncut/Estimates/UniformProduct.leanAdded+65
- lean/OAI/Computability/MinUncut/Estimates/UniformRestrict.leanAdded+195
- lean/OAI/Computability/MinUncut/Estimates/UniformSets.leanAdded+59
- lean/OAI/Computability/MinUncut/Estimates/UniformTransport.leanAdded+119
- lean/OAI/Computability/MinUncut/Estimates/WeightedTestLaw.leanAdded+187
- lean/OAI/Computability/MinUncut/Games/Actual.leanAdded+688
- lean/OAI/Computability/MinUncut/Games/AdaptiveKernel.leanAdded+83
- lean/OAI/Computability/MinUncut/Games/AffineLabels.leanAdded+91
- lean/OAI/Computability/MinUncut/Games/Basic.leanAdded+684
- lean/OAI/Computability/MinUncut/Games/FinalCNFHeader.leanAdded+733
- lean/OAI/Computability/MinUncut/Games/FinalCNFOutput.leanAdded+406
- lean/OAI/Computability/MinUncut/Games/FinalCNFPattern.leanAdded+103
- lean/OAI/Computability/MinUncut/Games/FinalCNFStream.leanAdded+688
- lean/OAI/Computability/MinUncut/Games/FiniteNoise.leanAdded+94
- lean/OAI/Computability/MinUncut/Games/GraphCounterModel.leanAdded+563
- lean/OAI/Computability/MinUncut/Games/GraphIterationBounds.leanAdded+77
- lean/OAI/Computability/MinUncut/Games/HintSections.leanAdded+83
- lean/OAI/Computability/MinUncut/Games/HintSimulation.leanAdded+154
- lean/OAI/Computability/MinUncut/Games/HintSoundness.leanAdded+74
- lean/OAI/Computability/MinUncut/Games/IncidenceProbability.leanAdded+527
- lean/OAI/Computability/MinUncut/Games/JointCoefficient.leanAdded+86
- lean/OAI/Computability/MinUncut/Games/JointHintBound.leanAdded+141
- lean/OAI/Computability/MinUncut/Games/JointHintSampling.leanAdded+74
- lean/OAI/Computability/MinUncut/Games/JointInner.leanAdded+208
- lean/OAI/Computability/MinUncut/Games/KernelSampling.leanAdded+208
- lean/OAI/Computability/MinUncut/Games/LabelBound.leanAdded+267
- lean/OAI/Computability/MinUncut/Games/MaskRowKernel.leanAdded+143
- lean/OAI/Computability/MinUncut/Games/OuterQuestions.leanAdded+757
- lean/OAI/Computability/MinUncut/Games/Parameters.leanAdded+110
- lean/OAI/Computability/MinUncut/Games/Pinsker.leanAdded+517
- lean/OAI/Computability/MinUncut/Games/PoweringGlobalEnumeration.leanAdded+91
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import Mathlibimport OAI.Computability.MinUncut.Estimates.InnerAssemblyimport OAI.Computability.MinUncut.Estimates.FourthTest
namespace OAI
sectionnoncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Compositionopen BinaryFourier hiding F₂open MinUncut.Inner RowNoiseattribute [local instance] Classical.propDecidable BinaryFourier.dualFintypevariable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] {m n : ℕ}
attribute [local irreducible] MinUncut.Inner.gradient
lemma oddAtom_iff_labelList {R : Type*} [Fintype R] [DecidableEq R] (r : R) (F : (R → Forms A) → ℝ) (D : Rest (W := Forms A) r) {θ : ℝ} (hθ : 0<θ) : θ≤oddAtom r (AffineMap.const F₂ A 1) F D ↔ (labelList (fun b => F (joinRow r b D)) θ).Nonempty := by constructor · intro h have he : ∃ α : Module.Dual F₂ (Forms A), oddAtom r (AffineMap.const F₂ A 1) F D = if α (AffineMap.const F₂ A 1)=1 then |rowCoefficient r F α D| else 0 := by obtain ⟨α,_,he⟩ := Finset.exists_mem_eq_sup' (s := Finset.univ) Finset.univ_nonempty (fun α : Module.Dual F₂ (Forms A) => if α (AffineMap.const F₂ A 1)=1 then |rowCoefficient r F α D| else 0) exact ⟨α,he⟩ obtain ⟨α,he⟩ := he rw [he] at h split_ifs at h with ho · obtain ⟨a,rfl⟩ := oddFrequency_exists_label α ho exact ⟨a, (mem_labelList _ θ a).mpr h⟩ · linarith · rintro ⟨a,ha⟩ exact ((mem_labelList _ θ a).mp ha).trans (rowCoefficient_le_oddAtom r (AffineMap.const F₂ A 1) F (labelFrequency a) (labelFrequency_odd a) D)
lemma rowAtom_iff_list (f : FoldedProof A) (σ η : ℝ) {θ : ℝ} (hθ : 0<θ) (x : Point m n) (i : Fin m) (D : Rest (W := Forms A) (⟨i,face x i⟩ : Row m n)) (c : Point m n → ℝ) : θ≤rowAtom f σ η x i D c ↔ (labelList (comparisonRow f σ η c x ⟨i,face x i⟩ D) θ).Nonempty := oddAtom_iff_labelList (⟨i,face x i⟩ : Row m n) (fun B => gradient f B σ η c x) D hθ
lemma rowAtomIndicator_eq_list (f : FoldedProof A) (σ η : ℝ) {θ : ℝ} (hθ : 0<θ) (x : Point m n) (i : Fin m) (D : Rest (W := Forms A) (⟨i,face x i⟩ : Row m n)) (c : Point m n → ℝ) : rowAtomIndicator f σ η θ x i D c = if (labelList (comparisonRow f σ η c x ⟨i,face x i⟩ D) θ).Nonempty then 1 else 0 := by simp only [rowAtomIndicator,rowAtom_iff_list f σ η hθ]
end MinUncut.Composition
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import Mathlibimport OAI.Computability.MinUncut.Estimates.SamplerCostimport OAI.Computability.MinUncut.Search.RationalDenominatorArithmetic
namespace OAI
sectionnoncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothnessattribute [local instance] Classical.propDecidable coordsDecEqvariable {Name I S : Type*} [Fintype I] [Fintype S] [Nonempty S]
lemma allWeight_mass (equations : S → Equation Name) {k m n : ℕ} (hk : k≤Fintype.card I) (g : GridData) (hT : 0<g.T) (hL : 0<g.L) (a : ℚ) (b : Test → ℚ) : (∑ e : AllElementary (I := I) equations k m n g, allWeight equations g a b e)=∑ j, (b j)⁻¹ := by apply (Rat.cast_injective (α := ℝ)) simp only [Rat.cast_sum,Rat.cast_inv,Fintype.sum_prod_type,allWeight, elementaryWeight_mass equations hk g hT hL]
structure Parameters (J : ℕ) where hJ : 1≤J d : InnerData hd : d.Check J o : OuterData ho : o.Check J d
namespace Parameters
def select (J : ℕ) (hJ : 1≤J) : Parameters J := let d := InnerData.search J hJ let hd := InnerData.search_check J hJ let o := OuterData.search J hJ d hd ⟨hJ,d,hd,o,OuterData.search_check J hJ d hd⟩
def grid {J : ℕ} (P : Parameters J) : GridData := 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)
lemma grid_pos {J : ℕ} (P : Parameters J) : 0<P.grid.T ∧ 0<P.grid.L := by have h := tableGrid_check P.d.m P.d.n (tableAccuracy J P.d P.o) (tableAccuracy_pos P.hJ P.d P.hd P.o P.ho) exact ⟨h.1,h.2.1⟩
lemma t_pos {J : ℕ} (P : Parameters J) : 0<P.o.t := P.ho.2.2.2.1lemma k_le {J : ℕ} (P : Parameters J) : P.o.k≤P.o.t := P.ho.2.2.2.2.1
def denominator {J : ℕ} (P : Parameters J) (S : Type*) [Fintype S] : ℕ := samplerDenominator (Fin P.o.t) S P.o.k P.d.m P.d.n P.grid (rationalRate J P.d) (rationalBudgets J P.d P.o)
lemma denominator_pos {J : ℕ} (P : Parameters J) : 0<P.denominator S := samplerDenominator_pos (by simpa only [Fintype.card_fin] using P.k_le) _ _ _
abbrev Sample {J : ℕ} (P : Parameters J) (equations : S → Equation Name) := AllElementary (I := Fin P.o.t) equations P.o.k P.d.m P.d.n P.grid
def weight {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (e : P.Sample equations) : ℚ := allWeight equations P.grid (rationalRate J P.d) (rationalBudgets J P.d P.o) e
def demand {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (e : P.Sample equations) : PathRealization.Demand (FamilyVariable Name (Fin P.o.t)) := allDemand equations P.grid (rationalSigma J) (rationalEta J) e
omit [Nonempty S] inlemma weight_nonneg {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (e : P.Sample equations) : 0≤P.weight equations e := elementaryWeight_nonneg equations P.grid P.grid_pos.1 P.grid_pos.2 (rationalRate_bounds P.hJ P.d P.hd).1 (rationalRate_bounds P.hJ P.d P.hd).2 (rationalBudgets_pos P.hJ P.d P.hd P.o P.ho e.1) e.1 e.2
lemma weight_den {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (e : P.Sample equations) : (P.weight equations e).den∣P.denominator S := elementaryWeight_den equations (by simpa only [Fintype.card_fin] using P.k_le) _ _ _ e.1 e.2
lemma weight_sum {J : ℕ} (P : Parameters J) (equations : S → Equation Name) : (∑ e, P.weight equations e)=rationalWeight J P.d P.o := allWeight_mass equations (by simpa only [Fintype.card_fin] using P.k_le) _ P.grid_pos.1 P.grid_pos.2 _ _
omit [Nonempty S] inlemma failure_eq {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (y : FamilyVariable Name (Fin P.o.t) → Bool) : (∑ e, (P.weight equations e:ℝ)*(PathRealization.failure (P.demand equations e) y:ℝ))= (variableProof y).finiteCost (P.d.realize P.hJ P.hd) (P.o.realize P.hJ P.d P.hd P.ho) P.grid equations := allFailure_eq P.hJ P.d P.hd P.o P.ho P.grid equations y
end Parametersend MinUncut.Outer
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import Mathlibimport OAI.Computability.MinUncut.Search.RationalInnerimport OAI.Computability.MinUncut.Estimates.WeightedTestLaw
namespace OAI
noncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothnessattribute [local instance] Classical.propDecidable coordsDecEqvariable {Name I S : Type*} [Fintype I] [Fintype S]
abbrev AllElementary (equations : S → Equation Name) (k m n : ℕ) (g : GridData) := Test × Elementary (I := I) equations k m n g
def allWeight (equations : S → Equation Name) {k m n : ℕ} (g : GridData) (a : ℚ) (b : Test → ℚ) (e : AllElementary (I := I) equations k m n g) : ℚ := elementaryWeight equations g a (b e.1) e.1 e.2
def allDemand (equations : S → Equation Name) {k m n : ℕ} (g : GridData) (σ η : ℚ) (e : AllElementary (I := I) equations k m n g) : PathRealization.Demand (FamilyVariable Name I) := (elementaryQuery equations g σ η e.1 e.2).signed familyBase
def rationalRate (J : ℕ) (d : InnerData) : ℚ := (rationalEta J)^2/d.m
lemma rationalRate_cast (J : ℕ) (d : InnerData) : (rationalRate J d:ℝ)=(sourceEta J)^2/d.m := by simp only [rationalRate,Rat.cast_div,Rat.cast_pow,Rat.cast_natCast,rationalEta_cast]
lemma rationalRate_bounds {J : ℕ} (hJ : 1≤J) (d : InnerData) (hd : d.Check J) : 0≤rationalRate J d ∧ rationalRate J d≤1 := by have ha := source_row_rate (by exact_mod_cast hJ : (1:ℝ)≤J) (by have := (d.realize hJ hd).hm; change 2≤d.m at this; omega : 0<d.m) rw [← rationalRate_cast] at ha exact ⟨by exact_mod_cast ha.1,by exact_mod_cast ha.2.1⟩
lemma allFailure_eq {J : ℕ} (hJ : 1≤J) (d : InnerData) (hd : d.Check J) (o : OuterData) (ho : o.Check J d) (g : GridData) (equations : S → Equation Name) (y : FamilyVariable Name I → Bool) : (∑ e : AllElementary (I := I) equations o.k d.m d.n g, (allWeight equations g (rationalRate J d) (rationalBudgets J d o) e:ℝ)* (PathRealization.failure (allDemand equations g (rationalSigma J) (rationalEta J) e) y:ℝ)) = (variableProof y).finiteCost (d.realize hJ hd) (o.realize hJ d hd ho) g equations := by rw [Fintype.sum_prod_type] unfold ProofFamily.finiteCost apply Finset.sum_congr rfl intro j _ simp only [allWeight,allDemand,QueryDemand.failure_signed,← variableProof_queryAnswer] rw [elementary_weighted_sum] cases j <;> simp only [ProofFamily.finiteErrors,rationalBudgets_cast hJ d hd o ho, rationalRate_cast] all_goals change edgeMean equations o.k (fun U h pos => _ / _) = edgeMean equations o.k (fun U h pos => _) / _ unfold edgeMean simp only [Finset.expect_div] rflend MinUncut.Outer
namespace MinUncut.Outeropen MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothnessattribute [local instance] Classical.propDecidable coordsDecEqvariable {m n : ℕ}
lemma noiseWeight_mean {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] (a : ℚ) (B : FaceArray A m n) (j : Test) : (𝔼 C, (noiseWeight a B C j:ℝ))=1 := by cases j with | second => have hh := RowNoise.rationalDensity_mean a B have hc := congrArg (fun x : ℚ => (x:ℝ)) hh simpa only [Fintype.expect_eq_sum_div_card,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast, Rat.cast_one,noiseWeight] using hc | first => simp only [noiseWeight,Rat.cast_one,Fintype.expect_const] | third => simp only [noiseWeight,Rat.cast_one,Fintype.expect_const] | fourth => simp only [noiseWeight,Rat.cast_one,Fintype.expect_const]
lemma gridWeight_mass (g : GridData) (hT : 0<g.T) (hL : 0<g.L) : (∑ q : TestCoordinates m n → Fin g.L, (gridWeight g q:ℝ))=1 := by exact_mod_cast sum_gridWeight (m := m) (n := n) g hT hL
lemma localWeight_mass {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] (g : GridData) (hT : 0<g.T) (hL : 0<g.L) (a b : ℚ) (j : Test) : (∑ p : LocalSample A m n g, (localWeight g a b j p:ℝ))=(b:ℝ)⁻¹ := by have hh := localWeight_sum (A := A) (m := m) (n := n) g a b j (fun _ => 1) simp only [mul_one,← Finset.sum_mul,gridWeight_mass g hT hL,one_mul,Fintype.expect_const, noiseWeight_mean,one_div] at hh exact hh
variable {Name I S : Type*} [Fintype I] [Fintype S] [Nonempty S] {k : ℕ}lemma elementaryWeight_mass (equations : S → Equation Name) (hk : k≤Fintype.card I) (g : GridData) (hT : 0<g.T) (hL : 0<g.L) (a b : ℚ) (j : Test) : (∑ e : Elementary (I := I) equations k m n g, (elementaryWeight equations g a b j e:ℝ))=(b:ℝ)⁻¹ := by let : Nonempty (FixedSets I k) := fixedSets_nonempty hk change (∑ e : Sigma _, _) = _ rw [Fintype.sum_sigma] simp only [elementaryWeight,Rat.cast_mul,Rat.cast_inv,Rat.cast_natCast,← Finset.mul_sum, localWeight_mass g hT hL] simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul] have hc : (Fintype.card (OuterSample I S k):ℝ)≠0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero field_simpend MinUncut.Outer
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259import Mathlibimport OAI.Computability.MinUncut.Analysis.SmoothingRhoimport OAI.Computability.MinUncut.Games.JointInnerimport OAI.Computability.MinUncut.Analysis.RowProjectedGradient
namespace OAI
noncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Filteropen scoped Topology NNRealopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Polynomial Filteropen scoped BigOperators Topologyopen MeasureTheory ProbabilityTheory WithLpopen scoped BigOperators RealInnerProductSpaceopen scoped BigOperatorsnamespace MinUncut.Inneropen MeasureTheory ProbabilityTheoryopen scoped BigOperatorsattribute [local instance] Classical.propDecidableattribute [local irreducible] query pullQueryvariable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]variable {m n : ℕ}
omit [Fintype A] inlemma secondFailure_indicator (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) (c : Point m n → ℝ) (p : (Point m n → ℝ) × (Code m n → ℝ)) : secondFailure f B C σ η c p = (coupledAnswer f B σ η c p-coupledAnswer f C σ η c p)^2/4 := by have h := secondFailure_eq f B C σ η c p linarith
lemma secondRejection_measurable (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) : Measurable (secondRejection f B C σ η) := by have hh (B : FaceArray A m n) : Measurable (fun u : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) => coupledAnswer f B σ η u.1 u.2) := by have hm : Measurable (fun u : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) => (u.1+σ•u.2.1,u.2.2)) := by fun_prop exact (measurable_answer f B η).comp hm have hm : Measurable (fun u : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) => secondFailure f B C σ η u.1 u.2) := by simp_rw [secondFailure_indicator] exact ((hh B).sub (hh C)).pow_const 2 |>.div_const 4 exact hm.stronglyMeasurable.integral_prod_right.measurable
lemma secondRejection_range (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) (c : Point m n → ℝ) : 0≤ secondRejection f B C σ η c ∧ secondRejection f B C σ η c≤1 := by have hm : Measurable (secondFailure f B C σ η c) := by change Measurable (fun p => secondFailure f B C σ η c p) simp_rw [secondFailure_indicator] exact ((coupledAnswer_measurable f B σ η c).sub (coupledAnswer_measurable f C σ η c)).pow_const 2 |>.div_const 4 have hb (p : (Point m n → ℝ) × (Code m n → ℝ)) : 0≤ secondFailure f B C σ η c p ∧ secondFailure f B C σ η c p≤1 := by unfold secondFailure; split_ifs <;> norm_num have hi : Integrable (secondFailure f B C σ η c) ((gauss (Point m n)).prod (gauss (Code m n))) := Integrable.of_bound hm.aestronglyMeasurable 1 (ae_of_all _ (fun p => by rw [Real.norm_eq_abs,abs_of_nonneg (hb p).1]; exact (hb p).2)) constructor · exact integral_nonneg (fun p => (hb p).1) · unfold secondRejection simpa only [integral_const,MeasureTheory.probReal_univ,one_smul] using integral_mono hi (integrable_const 1) (fun p => (hb p).2)
lemma secondRejection_integrable (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) : Integrable (secondRejection f B C σ η) (gauss (Point m n)) := Integrable.of_bound (secondRejection_measurable f B C σ η).aestronglyMeasurable 1 (ae_of_all _ (fun c => by rw [Real.norm_eq_abs,abs_of_nonneg (secondRejection_range f B C σ η c).1] exact (secondRejection_range f B C σ η c).2))
lemma rowProjectedGradient_memLp (D : ℕ) (f : FoldedProof A) (B : FaceArray A m n) {σ : ℝ} (hσ : σ≠0) (η : ℝ) (x : Point m n) : MemLp (fun c => rowProjectedGradient D f σ η B c x) 2 (gauss (Point m n)) := by unfold rowProjectedGradient RowNoise.project apply memLp_finsetSum intro α _ apply MemLp.mul_const unfold BinaryFourier.coefficient simp only [Fintype.expect_eq_sum_div_card, div_eq_mul_inv] exact (memLp_finsetSum _ (fun C _ => (gradient_memLp f C hσ η x).mul_const _)).mul_const _
lemma rowResidualEnergy_integrable (D : ℕ) (f : FoldedProof A) (B : FaceArray A m n) {σ : ℝ} (hσ : σ≠0) (η : ℝ) : Integrable (fun c => spatialEnergy (fun x => gradient f B σ η c x- rowProjectedGradient D f σ η B c x)) (gauss (Point m n)) := by unfold spatialEnergy exact (integrable_finsetSum _ (fun x _ => ((gradient_memLp f B hσ η x).sub (rowProjectedGradient_memLp D f B hσ η x)).integrable_sq)).const_mul _
theorem gradient_row_tail_average (f : FoldedProof A) (hn : 0 < n) {σ a : ℝ} (hσ : σ≠0) (ha : 0≤a) (ha1 : a≤1) (η : ℝ) (D : ℕ) (hD : ∀ k : ℕ, D < k → 1≤(k:ℝ)*a) : (𝔼 B : FaceArray A m n, ∫ c, spatialEnergy (fun x => gradient f B σ η c x-rowProjectedGradient D f σ η B c x) ∂gauss (Point m n)) ≤ 4*σ⁻¹^2*(𝔼 B : FaceArray A m n, 𝔼 C : FaceArray A m n, RowNoise.density a B C*(∫ c, secondRejection f B C σ η c ∂gauss (Point m n))) := by have hl : Integrable (fun c => 𝔼 B : FaceArray A m n, spatialEnergy (fun x => gradient f B σ η c x-rowProjectedGradient D f σ η B c x)) (gauss (Point m n)) := by simp only [Fintype.expect_eq_sum_div_card] exact (integrable_finsetSum _ (fun B _ => rowResidualEnergy_integrable D f B hσ η)).div_const _ have hr : Integrable (fun c => 4*σ⁻¹^2*(𝔼 B : FaceArray A m n, 𝔼 C : FaceArray A m n, RowNoise.density a B C*secondRejection f B C σ η c)) (gauss (Point m n)) := by simp only [Fintype.expect_eq_sum_div_card] apply Integrable.const_mul apply Integrable.div_const apply integrable_finsetSum intro B _ exact (integrable_finsetSum _ (fun C _ => (secondRejection_integrable f B C σ η).const_mul _)).div_const _ have h := integral_mono hl hr (fun c => gradient_row_tail f hn hσ ha ha1 η D hD c) simpa only [Fintype.expect_eq_sum_div_card,integral_div,integral_const_mul, integral_finsetSum _ (fun B _ => rowResidualEnergy_integrable D f B hσ η), integral_finsetSum _ (fun B _ => (integrable_finsetSum _ (fun C _ => (secondRejection_integrable f B C σ η).const_mul _)).div_const _), integral_finsetSum _ (fun C _ => (secondRejection_integrable f _ C σ η).const_mul _)] using hend MinUncut.Innernamespace MinUncut.RowNoiseopen MeasureTheory ProbabilityTheory BinaryFourier GaussianHermiteopen scoped BigOperatorsattribute [local instance] Classical.propDecidablelocal instance secondFailureDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] : Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintypevariable {R W ι : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W] [AddCommGroup W] [Module F₂ W] [Fintype ι] [DecidableEq ι]
lemma project_eq_mask_sum (D : ℕ) (f : (R → W) → ℝ) (B : R → W) : project D f B = ∑ S ∈ Finset.univ.filter (fun S : Finset R => S.card ≤ D), maskProject S f B := by simp only [maskProject_expansion] rw [Finset.sum_comm] simp only [Finset.sum_filter] unfold project rw [Finset.sum_filter] apply Finset.sum_congr rfl intro α _ rw [Finset.sum_eq_single (mask α)] · simp [degree] rfl · intro S _ hS simp [Ne.symm hS] · simp
omit [DecidableEq W] inlemma project_sum {T : Type*} (s : Finset T) (D : ℕ) (u : T → (R → W) → ℝ) (B : R → W) : project D (fun C => ∑ t ∈ s, u t C) B = ∑ t ∈ s, project D (u t) B := by unfold project BinaryFourier.coefficient simp only [Finset.sum_mul,Finset.expect_sum_comm] rw [Finset.sum_comm]
omit [DecidableEq W] inlemma project_sub (D : ℕ) (f g : (R → W) → ℝ) (B : R → W) : project D (fun C => f C-g C) B = project D f B-project D g B := by simp only [project,BinaryFourier.coefficient,sub_mul,Finset.expect_sub_distrib,Finset.sum_sub_distrib]
omit [DecidableEq W] inlemma project_energy_le (D : ℕ) (f : (R → W) → ℝ) : (𝔼 B, (project D f B)^2) ≤ 𝔼 B, (f B)^2 := by rw [← BinaryFourier.parseval,← BinaryFourier.parseval] simp only [coefficient_project] apply Finset.sum_le_sum intro α _ split_ifs <;> simp [sq_nonneg]
omit [DecidableEq ι] inlemma project_memLp (D : ℕ) (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) (B : R → W) : MemLp (fun c => project D (fun C => u C c) B) 2 (γpi ι) := by simp_rw [project_eq_mask_sum] exact memLp_finsetSum _ (fun S _ => memLp_maskProject S u hu B)
def rectangle (D s : ℕ) : Finset (Finset R × (ι → ℕ)) := (Finset.univ.filter (fun S : Finset R => S.card≤D)).product (GaussianHermite.low s)
lemma rectangle_eq_composition (D s : ℕ) (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) (c : ι → ℝ) : selectedProject (rectangle D s) u B c = project D (fun C => GaussianHermite.project s (u C) c) B := by unfold selectedProject rectangle have he := Finset.sum_product (Finset.univ.filter (fun S : Finset R => S.card≤D)) (GaussianHermite.low s) (fun j => maskHermite j.1 j.2 u B c) change (∑ j ∈ (Finset.univ.filter (fun S : Finset R => S.card≤D)) ×ˢ (GaussianHermite.low s), maskHermite j.1 j.2 u B c) = _ rw [he] simp only [GaussianHermite.project] rw [project_sum] simp only [project_eq_mask_sum] rw [Finset.sum_comm] apply Finset.sum_congr rfl intro I _ apply Finset.sum_congr rfl intro S _ simp only [maskHermite,hermiteComponent,mul_comm]
omit [DecidableEq ι] inlemma jointEnergy_project_le (D : ℕ) (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) : jointEnergy (fun B c => project D (fun C => u C c) B) ≤ jointEnergy u := by unfold jointEnergy rw [← integral_expect _ (fun B => (project_memLp D u hu B).integrable_sq), ← integral_expect _ (fun B => (hu B).integrable_sq)] apply integral_mono · simp only [Fintype.expect_eq_sum_div_card] exact (integrable_finsetSum _ (fun B _ => (project_memLp D u hu B).integrable_sq)).div_const _ · simp only [Fintype.expect_eq_sum_div_card] exact (integrable_finsetSum _ (fun B _ => (hu B).integrable_sq)).div_const _ · intro c; exact project_energy_le D (fun B => u B c)
omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] [DecidableEq ι] inlemma jointEnergy_add_le (u v : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) (hv : ∀ B, MemLp (v B) 2 (γpi ι)) : jointEnergy (fun B c => u B c+v B c) ≤ 2*jointEnergy u+2*jointEnergy v := by have hB (B : R → W) : (∫ c, (u B c+v B c)^2 ∂γpi ι) ≤ 2*(∫ c, (u B c)^2 ∂γpi ι)+2*(∫ c, (v B c)^2 ∂γpi ι) := by calc _ ≤ ∫ c, 2*(u B c)^2+2*(v B c)^2 ∂γpi ι := integral_mono ((hu B).add (hv B)).integrable_sq (((hu B).integrable_sq.const_mul 2).add ((hv B).integrable_sq.const_mul 2)) (fun c => by change (u B c+v B c)^2 ≤ 2*(u B c)^2+2*(v B c)^2 nlinarith [sq_nonneg (u B c-v B c)]) _ = _ := by rw [integral_add ((hu B).integrable_sq.const_mul 2) ((hv B).integrable_sq.const_mul 2),integral_const_mul,integral_const_mul] simpa only [jointEnergy,Finset.expect_add_distrib,← Finset.mul_expect] using Finset.expect_le_expect (s := Finset.univ) (fun B _ => hB B)
theorem rectangle_residual_le (D s : ℕ) (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) : jointEnergy (fun B c => u B c-selectedProject (rectangle D s) u B c) ≤ 2*jointEnergy (fun B c => u B c-project D (fun C => u C c) B)+ 2*jointEnergy (fun B c => u B c-GaussianHermite.project s (u B) c) := by let v := fun B c => u B c-project D (fun C => u C c) B let w := fun B c => u B c-GaussianHermite.project s (u B) c have hv (B) : MemLp (v B) 2 (γpi ι) := (hu B).sub (project_memLp D u hu B) have hw (B) : MemLp (w B) 2 (γpi ι) := (hu B).sub (GaussianHermite.memLp_project s (u B)) have he (B c) : u B c-selectedProject (rectangle D s) u B c = v B c+project D (fun C => w C c) B := by rw [rectangle_eq_composition] simp only [v,w,project_sub] ring simp_rw [he] exact (jointEnergy_add_le v (fun B c => project D (fun C => w C c) B) hv (project_memLp D w hw)).trans (add_le_add_right (mul_le_mul_of_nonneg_left (jointEnergy_project_le D w hw) (show (0 : ℝ) ≤ 2 by norm_num)) _)
lemma rectangle_energy_identity (D s : ℕ) (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) : jointEnergy (selectedProject (rectangle D s) u) = jointEnergy u- jointEnergy (fun B c => u B c-selectedProject (rectangle D s) u B c) := by rw [jointEnergy_sub u _ hu (memLp_selectedProject _ _), selectedProject_source_inner _ u hu,← selectedProject_energy] ringend MinUncut.RowNoise
end
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import Mathlibimport OAI.Computability.MinUncut.Analysis.MaskHermite
namespace OAI
noncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Filteropen scoped Topology NNRealopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Polynomial Filteropen scoped BigOperators Topologyopen MeasureTheory ProbabilityTheory WithLpopen scoped BigOperators RealInnerProductSpacenamespace MinUncut.RowNoiseopen MeasureTheory ProbabilityTheory BinaryFourier GaussianHermiteopen scoped BigOperatorslocal instance selectedProjectDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] : Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintypevariable {R W ι : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W] [AddCommGroup W] [Module F₂ W] [Fintype ι]
def selectedProject (J : Finset (Finset R × (ι → ℕ))) (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) (c : ι → ℝ) : ℝ := ∑ j ∈ J, maskHermite j.1 j.2 u B c
omit [AddCommGroup W] [Module F₂ W] inlemma memLp_selectedProject (J : Finset (Finset R × (ι → ℕ))) (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) : MemLp (selectedProject J u B) 2 (γpi ι) := memLp_finsetSum _ (fun j _ => memLp_maskHermite j.1 j.2 u B)
lemma selectedProject_atom_mean (J : Finset (Finset R × (ι → ℕ))) (r : R) (one : W) (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) : (𝔼 D, ∫ c, oddAtom r one (fun B => selectedProject J u B c) D ∂γpi ι) ≤ J.card * (2:ℝ)^Fintype.card R * Real.sqrt (𝔼 D, ∫ c, (oddAtom r one (fun B => u B c) D)^2 ∂γpi ι) := by have hi (D : Rest (W := W) r) := (memLp_oddAtom r one (selectedProject J u) (memLp_selectedProject J u) D).integrable (by norm_num) have hj (j : Finset R × (ι → ℕ)) (D : Rest (W := W) r) := (memLp_oddAtom r one (maskHermite j.1 j.2 u) (memLp_maskHermite j.1 j.2 u) D).integrable (by norm_num) calc _ ≤ 𝔼 D, ∫ c, (∑ j ∈ J, oddAtom r one (fun B => maskHermite j.1 j.2 u B c) D) ∂γpi ι := by apply Finset.expect_le_expect intro D _ exact integral_mono (hi D) (integrable_finsetSum _ (fun j _ => hj j D)) (fun c => oddAtom_sum J r one (fun j B => maskHermite j.1 j.2 u B c) D) _ = ∑ j ∈ J, 𝔼 D, ∫ c, oddAtom r one (fun B => maskHermite j.1 j.2 u B c) D ∂γpi ι := by simp_rw [integral_finsetSum _ (fun j _ => hj j _), Finset.expect_sum_comm] _ ≤ ∑ _j ∈ J, (2:ℝ)^Fintype.card R * Real.sqrt (𝔼 D, ∫ c, (oddAtom r one (fun B => u B c) D)^2 ∂γpi ι) := Finset.sum_le_sum (fun j _ => oddAtom_maskHermite_mean r one j.1 j.2 u hu) _ = _ := by simp only [Finset.sum_const, nsmul_eq_mul]; ringend MinUncut.RowNoiseopen scoped BigOperators
end
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import Mathlibimport OAI.Computability.MinUncut.Estimates.FaceUpdateSelfimport OAI.Computability.MinUncut.Games.JointInner
namespace OAI
noncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Filteropen scoped Topology NNRealopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Polynomial Filteropen scoped BigOperators Topologyopen MeasureTheory ProbabilityTheory WithLpopen scoped BigOperators RealInnerProductSpaceopen scoped BigOperatorsnamespace MinUncut.RowNoiseopen MeasureTheory GaussianHermiteopen scoped BigOperatorsvariable {R W ι : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W] [AddCommGroup W] [Module BinaryFourier.F₂ W] [Fintype ι] [DecidableEq ι]omit [AddCommGroup W] [Module BinaryFourier.F₂ W] inlemma selectedProject_slice_continuous (J : Finset (Finset R × (ι → ℕ))) (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) (C : ι → ℝ) (x : ι) : Continuous (fun t => selectedProject J u B (Function.update C x t)) := by have hu : Continuous (fun t => Function.update C x t) := by apply continuous_pi intro y by_cases hy : y=x · subst y simp only [Function.update_self] exact continuous_id · simp only [Function.update_of_ne hy] exact continuous_const unfold selectedProject apply continuous_finsetSum intro j _ simp only [maskHermite_eq] exact ((continuous_psi j.2).comp hu).mul_const _end MinUncut.RowNoise
namespace MinUncut.Sliceopen MeasureTheoryvariable {Ω : Type*} [MeasurableSpace Ω] [TopologicalSpace Ω]lemma centeredClip_continuous (μ : Measure Ω) (A : ℝ) (f : Ω → ℝ) (hf : Continuous f) : Continuous (centeredClip μ A f) := by unfold centeredClip clip exact (continuous_const.max (hf.min continuous_const)).sub continuous_constend MinUncut.Slice
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import Mathlibimport OAI.Computability.MinUncut.Graphs.CompleteGraphProgramimport OAI.Computability.MinUncut.Graphs.Graph
namespace OAI
sectionnoncomputable sectionnamespace MinUncut.Preprocessattribute [local irreducible] selectedInner selectedOuteropen MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplateopen MinUncutGames.Foundations MinUncutGames.Foundations.Hastadopen MinUncutGames.Integration.SourceParameters MinUncut.Costed.SourceWords MinUncut.SourceTemplatedef chosenError (K : ℕ) := (selectedParameters K).sourceErrordef chosenNoise (K : ℕ) := SourceNoiseParameter.noiseDenominator (chosenError K)def chosenRepetition (K : ℕ) := SourceGap.repetitionCount PCP.PCPIteration.finalClauseGap (chosenError K) PCP.PCPIteration.finalClauseGap_positive PCP.TableGapReduction.finalClauseGap_le_one (selectedParameters K).sourceError_pos (chosenNoise K) (SourceNoiseParameter.noiseDenominator_pos _)lemma c_chosenError : Computable chosenError := by have hd := ca_ratDiv (c_outerData_b4.comp c_selectedOuter) (ca_ratCast c_chosenT) have hp:=ca_ratLe (ca_const (1/2:ℚ)) hd exact (Computable.cond hp.decide (ca_const (1/2:ℚ)) hd).of_eq (by intro K; simp [chosenError,Outer.Parameters.sourceError,min_def,selectedParameters,chosenT])lemma c_chosenNoise : Computable chosenNoise := by exact ca_add (primrec_ratDen.to_comp.comp c_chosenError) (ca_const 2)lemma c_chosenRepetition : Computable chosenRepetition := by apply Computable.find exact ca_and (ca_natLt (ca_const 0) Computable.snd) (ca_ratLt (ca_ratPow (ca_const (rate (PCP.PCPIteration.finalClauseGap/3))) Computable.snd) (ca_ratMul (ca_ratMul (ca_const 4) (ca_ratInv (ca_ratCast (c_chosenNoise.comp Computable.fst)))) (ca_ratPow (c_chosenError.comp Computable.fst) (ca_const 2))))attribute [local irreducible] chosenRepetition chosenNoise sourceStageProgramlemma c_selectedGraphCode : Computable (fun K=> (completeGraphProgram (selectedParameters K) (chosenEnumeration K) (chosenRepetition K) (chosenNoise K)).code) := by have hd := Syntax.c_demandStageCode _ c_chosenExpressions chosenT (fun K=>(selectedParameters K).denominatorCoefficient) c_chosenT c_chosenDenominator have hs := Syntax.c_sourceStageCode.comp (c_chosenRepetition.pair c_chosenNoise) have hc : Computable (fun K => Turing.ToPartrec.Code.comp (Turing.ToPartrec.Code.comp MinUncut.Costed.GraphRegisters.rawRenderer.code (demandStageProgram (localExpressions (chosenEnumeration K) (rationalRate (parameterJ K) (selectedInner K)) (rationalBudgets (parameterJ K) (selectedInner K) (selectedOuter K)) (rationalSigma (parameterJ K)) (rationalEta (parameterJ K))) (chosenT K) (selectedParameters K).denominatorCoefficient).code) (sourceStageProgram (chosenRepetition K) (chosenNoise K)).code) := MinUncut.CodeEffective.computable_comp.comp (MinUncut.CodeEffective.computable_comp.comp (ca_const MinUncut.Costed.GraphRegisters.rawRenderer.code) hd) hs apply hc.of_eq intro K rflend MinUncut.Preprocess
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import Mathlibimport OAI.Computability.MinUncut.Games.JointCoefficientimport OAI.Computability.MinUncut.Analysis.Hermite
namespace OAI
noncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Filteropen scoped Topology NNRealopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Polynomial Filteropen scoped BigOperators Topologyopen MeasureTheory ProbabilityTheory WithLpopen scoped BigOperators RealInnerProductSpacenamespace MinUncut.Inneropen scoped BigOperatorsattribute [local instance] Classical.propDecidablevariable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]variable {m n : ℕ}
def singleRow (r : Row m n) : Row m n → F₂ := Pi.single r 1
lemma rowCode_singleRow (r : Row m n) (u : Point m n) : (rowCode (singleRow r)).val u = if face u r.1=r.2 then 1 else 0 := by change (∑ i : Fin m, (Pi.single r (1:F₂) : Row m n → F₂) ⟨i,face u i⟩) = _ rw [Finset.sum_eq_single r.1] · by_cases hh : face u r.1=r.2 · simp [hh] · have he : (⟨r.1,face u r.1⟩ : Row m n) ≠ r := by intro he; cases r; simp_all simp [hh, Pi.single_eq_of_ne he] · intro i _ hi apply Pi.single_eq_of_ne intro he exact hi (congrArg Sigma.fst he) · simp
omit [Fintype A] inlemma constantArray_singleRow (r : Row m n) : constantArray (singleRow r) = Pi.single r (AffineMap.const F₂ A 1) := by funext t by_cases ht : t=r · subst t; simp [constantArray, singleRow] · simp only [constantArray, singleRow, Pi.single_eq_of_ne ht] rfl
theorem joint_local_odd (f : FoldedProof A) {σ : ℝ} (hσ : σ ≠ 0) (η : ℝ) (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ) (hne : jointCoefficient f σ η x α I ≠ 0) (i : Fin m) (hi : ∀ u, 0 < I u → face u i ≠ face x i) : RowNoise.frequency α ⟨i,face x i⟩ (AffineMap.const F₂ A 1) = 1 := by have hh := joint_row_gauge f hσ η x α I hne (singleRow ⟨i,face x i⟩) rw [constantArray_singleRow, rowCode_singleRow, ite_eq_left rfl] at hh have hp : GaussianHermite.parity (rowCode (singleRow ⟨i,face x i⟩)).val I = 0 := by unfold GaussianHermite.parity apply Finset.sum_eq_zero intro u _ by_cases hu : I u=0 · simp [hu] · rw [rowCode_singleRow, ite_eq_right (hi u (Nat.pos_of_ne_zero hu)), zero_mul] rw [hp, add_zero] at hh exact hh
lemma frequency_cylinder (α : Module.Dual F₂ (FaceArray A m n)) (x : Point m n) (i j : Fin m) (hij : i ≠ j) (hi : ∀ y, RowNoise.frequency α ⟨i,y⟩ ≠ 0 → doubleMatch i j x (rowFill x ⟨i,y⟩) → y=face x i) (hj : ∀ y, RowNoise.frequency α ⟨j,y⟩ ≠ 0 → doubleMatch j i x (rowFill x ⟨j,y⟩) → y=face x j) (a : Forms A) : α (cylinderArray i j x a) = RowNoise.frequency α ⟨i,face x i⟩ a + RowNoise.frequency α ⟨j,face x j⟩ a := by rw [RowNoise.dual_apply] have he (r : Row m n) : RowNoise.frequency α r (cylinderArray i j x a r) = (if r=⟨i,face x i⟩ then RowNoise.frequency α ⟨i,face x i⟩ a else 0) + (if r=⟨j,face x j⟩ then RowNoise.frequency α ⟨j,face x j⟩ a else 0) := by by_cases hr : r=⟨i,face x i⟩ · subst r have hne : (⟨i,face x i⟩ : Row m n) ≠ ⟨j,face x j⟩ := by intro he; exact hij (congrArg Sigma.fst he) simp [hne, cylinderArray_local, doubleMatch] by_cases hr' : r=⟨j,face x j⟩ · subst r simp [hr, cylinderArray_local, doubleMatch] simp only [ite_eq_right hr, ite_eq_right hr', zero_add] by_cases ha : RowNoise.frequency α r=0 · simp [ha] · unfold cylinderArray split_ifs with hc · rcases r with ⟨t,y⟩ rcases hc.1 with ht | ht · change t=i at ht subst t exact False.elim (hr (by rw [hi y ha hc.2])) · change t=j at ht subst t have hc' : doubleMatch j i x (rowFill x ⟨j,y⟩) := fun u huj hui => hc.2 u hui huj exact False.elim (hr' (by rw [hj y ha hc'])) · simp simp_rw [he] rw [Finset.sum_add_distrib] simp
theorem joint_matching_odd (f : FoldedProof A) {σ : ℝ} (hσ : σ ≠ 0) (η : ℝ) (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ) (hne : jointCoefficient f σ η x α I ≠ 0) (hx : I x=0) (hsize : (RowNoise.mask α).card < (m-(∑ u, I u)).choose 2) : ∃ i j : Fin m, i ≠ j ∧ RowNoise.frequency α ⟨i,face x i⟩ = RowNoise.frequency α ⟨j,face x j⟩ ∧ RowNoise.frequency α ⟨i,face x i⟩ (AffineMap.const F₂ A 1) = 1 := by obtain ⟨i,j,hij,hs,hi,hj⟩ := admissible_pair x I (RowNoise.mask α) hx hsize refine ⟨i,j,hij,?_,joint_local_odd f hσ η x α I hne i (fun u hu => (hs u hu).1)⟩ apply LinearMap.ext intro a have hh := joint_cylinder_gauge f σ η x α I hne i j hij x a rw [frequency_cylinder α x i j hij (fun y hy => hi y (by simpa [RowNoise.mask] using hy)) (fun y hy => hj y (by simpa [RowNoise.mask] using hy))] at hh exact (BinaryFourier.add_eq_zero_iff _ _).mp hhend MinUncut.Inner
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724import Mathlibimport OAI.Computability.MinUncut.Estimates.CodeComputability
namespace OAI
sectionnamespace MinUncut.Costed
open Function
def Steps {α : Type*} (f : α → Option α) (n : ℕ) (a b : α) : Prop := (fun x : Option α => x.bind f)^[n] (some a) = some b
@[simp] theorem steps_zero {α : Type*} (f : α → Option α) (a b : α) : Steps f 0 a b ↔ a = b := by simp [Steps]
theorem steps_one {α : Type*} {f : α → Option α} {a b : α} (h : f a = some b) : Steps f 1 a b := h
theorem steps_head {α : Type*} {f : α → Option α} {n : ℕ} {a b c : α} (h : f a = some b) (h' : Steps f n b c) : Steps f (n + 1) a c := by simpa only [Steps, Function.iterate_succ_apply, Option.bind_some, h] using h'
theorem steps_trans {α : Type*} {f : α → Option α} {m n : ℕ} {a b c : α} (h : Steps f m a b) (h' : Steps f n b c) : Steps f (m + n) a c := by dsimp [Steps] at * rw [Nat.add_comm m n, Function.iterate_add_apply, h, h']
def steps_timed {α : Type*} {f : α → Option α} {n m : ℕ} {a b : α} (h : Steps f n a b) (hn : n ≤ m) : StateTransition.EvalsToInTime f a (some b) m := ⟨⟨n, h⟩, hn⟩
def Within {α : Type*} (f : α → Option α) (n : ℕ) (a b : α) : Prop := ∃ t, t ≤ n ∧ Steps f t a b
theorem Steps.within {α : Type*} {f : α → Option α} {n : ℕ} {a b : α} (h : Steps f n a b) : Within f n a b := ⟨n, le_rfl, h⟩
theorem Within.mono {α : Type*} {f : α → Option α} {m n : ℕ} {a b : α} (h : Within f m a b) (hmn : m ≤ n) : Within f n a b := by obtain ⟨t, ht, he⟩ := h exact ⟨t, ht.trans hmn, he⟩
theorem Within.trans {α : Type*} {f : α → Option α} {m n : ℕ} {a b c : α} (h : Within f m a b) (h' : Within f n b c) : Within f (m + n) a c := by obtain ⟨t, ht, he⟩ := h obtain ⟨t', ht', he'⟩ := h' exact ⟨t+t', Nat.add_le_add ht ht', steps_trans he he'⟩
theorem Within.head {α : Type*} {f : α → Option α} {n : ℕ} {a b c : α} (h : f a = some b) (h' : Within f n b c) : Within f (n + 1) a c := by obtain ⟨t, ht, he⟩ := h' exact ⟨t+1, Nat.add_le_add_right ht 1, steps_head h he⟩
theorem within_one {α : Type*} {f : α → Option α} {a b : α} (h : f a = some b) : Within f 1 a b := (steps_one h).within
end MinUncut.Costed
namespace Turing.PartrecToTM2open scoped _root_.Turing _root_.Turing.PartrecToTM2open Functionopen MinUncut.Costedopen _root_.Turing.PartrecToTM2.K'
theorem move_steps {p k₁ k₂ q s L₁ o L₂} {S : _root_.Turing.PartrecToTM2.K' → List _root_.Turing.PartrecToTM2.Γ'} (h₁ : k₁ ≠ k₂) (e : _root_.Turing.PartrecToTM2.splitAtPred p (S k₁) = (L₁, o, L₂)) : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (L₁.length + 1) ⟨some (_root_.Turing.PartrecToTM2.Λ'.move p k₁ k₂ q), s, S⟩ ⟨some q, o, update (update S k₁ L₂) k₂ (L₁.reverseAux (S k₂))⟩ := by induction L₁ generalizing S s with | nil => rw [(_ : [].reverseAux _ = _), Function.update_eq_self] swap · rw [Function.update_of_ne h₁.symm, List.reverseAux_nil] apply steps_one simp only [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.tr_move, _root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux, Option.elim] grind [_root_.Turing.PartrecToTM2.splitAtPred.eq_def] | cons a L₁ IH => refine steps_head rfl ?_ rw [_root_.Turing.PartrecToTM2.tr]; simp only [_root_.Turing.PartrecToTM2.pop', Option.elim, _root_.Turing.TM2.stepAux, _root_.Turing.PartrecToTM2.push'] rcases e₁ : S k₁ with - | ⟨a', Sk⟩ <;> rw [e₁, _root_.Turing.PartrecToTM2.splitAtPred] at e · cases e cases e₂ : p a' <;> simp only [e₂, cond] at e swap · cases e rcases e₃ : _root_.Turing.PartrecToTM2.splitAtPred p Sk with ⟨_, _, _⟩ rw [e₃] at e cases e simp only [List.head?_cons, e₂, List.tail_cons, Bool.cond_false] convert! @IH _ (update (update S k₁ Sk) k₂ (a :: S k₂)) _ using 2 <;> simp [Function.update_of_ne, h₁, h₁.symm, e₃, List.reverseAux] simp [Function.update_comm h₁.symm]
theorem clear_steps {p k q s L₁ o L₂} {S : _root_.Turing.PartrecToTM2.K' → List _root_.Turing.PartrecToTM2.Γ'} (e : _root_.Turing.PartrecToTM2.splitAtPred p (S k) = (L₁, o, L₂)) : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (L₁.length + 1) ⟨some (_root_.Turing.PartrecToTM2.Λ'.clear p k q), s, S⟩ ⟨some q, o, update S k L₂⟩ := by induction L₁ generalizing S s with | nil => apply steps_one simp only [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.tr_clear, _root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux] grind [_root_.Turing.PartrecToTM2.splitAtPred.eq_def] | cons a L₁ IH => refine steps_head rfl ?_ rw [_root_.Turing.PartrecToTM2.tr]; simp only [_root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux, Option.elim] rcases e₁ : S k with - | ⟨a', Sk⟩ <;> rw [e₁, _root_.Turing.PartrecToTM2.splitAtPred] at e · cases e cases e₂ : p a' <;> simp only [e₂, cond] at e swap · cases e rcases e₃ : _root_.Turing.PartrecToTM2.splitAtPred p Sk with ⟨_, _, _⟩ rw [e₃] at e cases e simp only [List.head?_cons, e₂, List.tail_cons, Bool.cond_false] convert! @IH _ (update S k Sk) _ using 2 <;> simp [e₃]
theorem unrev_steps {q s} {S : _root_.Turing.PartrecToTM2.K' → List _root_.Turing.PartrecToTM2.Γ'} : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) ((S rev).length + 1) ⟨some (_root_.Turing.PartrecToTM2.unrev q), s, S⟩ ⟨some q, none, update (update S rev []) main (List.reverseAux (S rev) (S main))⟩ := move_steps (by decide) (_root_.Turing.PartrecToTM2.splitAtPred_false _)
theorem copy_steps (q s a b c d) : 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⟩ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (List.reverseAux b a) [] c (List.reverseAux b d)⟩ := by induction b generalizing a d s with | nil => apply steps_one simp [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.tr, _root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux] | cons x b IH => refine steps_head rfl ?_ rw [_root_.Turing.PartrecToTM2.tr] simp only [_root_.Turing.TM2.stepAux, elim_rev, List.head?_cons, Option.isSome_some, List.tail_cons, elim_update_rev, elim_main, elim_update_main, elim_stack, elim_update_stack, Bool.cond_true, List.reverseAux_cons, _root_.Turing.PartrecToTM2.pop', _root_.Turing.PartrecToTM2.push'] exact IH _ _ _
theorem move₂_steps {p k₁ k₂ q s L₁ o L₂} {S : _root_.Turing.PartrecToTM2.K' → List _root_.Turing.PartrecToTM2.Γ'} (h₁ : k₁ ≠ rev ∧ k₂ ≠ rev ∧ k₁ ≠ k₂) (h₂ : S rev = []) (e : _root_.Turing.PartrecToTM2.splitAtPred p (S k₁) = (L₁, o, L₂)) : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2 * L₁.length + 3) ⟨some (_root_.Turing.PartrecToTM2.move₂ p k₁ k₂ q), s, S⟩ ⟨some q, none, update (update S k₁ (o.elim id List.cons L₂)) k₂ (L₁ ++ S k₂)⟩ := by have heq : 2 * L₁.length + 3 = (L₁.length + 1) + ((L₁.length + 1) + 1) := by omega rw [heq] refine steps_trans (move_steps h₁.1 e) (steps_head rfl ?_) cases o <;> rw [_root_.Turing.PartrecToTM2.tr] <;> simp only [id, _root_.Turing.TM2.stepAux, Option.isSome, Bool.cond_true, Bool.cond_false, Option.elim] · convert! move_steps h₁.2.1.symm (_root_.Turing.PartrecToTM2.splitAtPred_false _) using 2 · simp [Function.update_self, List.reverseAux_eq, h₂] simp only [Function.update_comm h₁.1, Function.update_idem] rw [show update S rev [] = S by rw [← h₂, Function.update_eq_self]] simp only [Function.update_of_ne h₁.2.2.symm, Function.update_of_ne h₁.2.1, Function.update_of_ne h₁.1.symm, List.reverseAux_eq, h₂, Function.update_self, List.append_nil, List.reverse_reverse] · simp only [Option.getD_some] convert! move_steps h₁.2.1.symm (_root_.Turing.PartrecToTM2.splitAtPred_false _) using 2 · simp [Function.update_self, Function.update_of_ne h₁.1.symm, List.reverseAux_eq, h₂] simp only [h₂, Function.update_comm h₁.1, List.reverseAux_eq, Function.update_self, List.append_nil, Function.update_idem] rw [show update S rev [] = S by rw [← h₂, Function.update_eq_self]] simp only [Function.update_of_ne h₁.1.symm, Function.update_of_ne h₁.2.2.symm, Function.update_of_ne h₁.2.1, Function.update_self, List.reverse_reverse]
theorem head_main_steps {q s L} {c d : List _root_.Turing.PartrecToTM2.Γ'} : 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) ⟨some (_root_.Turing.PartrecToTM2.head main q), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList L) [] c d⟩ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList [L.headI]) [] c d⟩ := by let o : Option _root_.Turing.PartrecToTM2.Γ' := List.casesOn L none fun _ _ => some _root_.Turing.PartrecToTM2.Γ'.cons have heq : 2*(_root_.Turing.PartrecToTM2.trNat L.headI).length+(_root_.Turing.PartrecToTM2.trList L.tail).length+6 = ((_root_.Turing.PartrecToTM2.trNat L.headI).length+1) + ((((_root_.Turing.PartrecToTM2.trList L.tail).length+1)+((_root_.Turing.PartrecToTM2.trNat L.headI).length+2)+1)+1) := by omega rw [heq] refine steps_trans (move_steps (by decide) (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ (_root_.Turing.PartrecToTM2.trNat L.headI) o (_root_.Turing.PartrecToTM2.trList L.tail) (_root_.Turing.PartrecToTM2.trNat_natEnd _) ?_)) (steps_head rfl (steps_head rfl ?_)) · cases L <;> simp [o] rw [_root_.Turing.PartrecToTM2.tr] simp only [_root_.Turing.TM2.stepAux, elim_update_main, elim_rev, elim_update_rev, Function.update_self, _root_.Turing.PartrecToTM2.trList] rw [ite_eq_right (show o ≠ some _root_.Turing.PartrecToTM2.Γ'.consₗ by cases L <;> simp [o])] refine steps_trans (clear_steps (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ _ none [] ?_ ⟨rfl,rfl⟩)) ?_ · exact fun x h => Bool.decide_false (_root_.Turing.PartrecToTM2.trList_ne_consₗ _ _ h) simpa [List.reverseAux_eq] using (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))
theorem head_stack_time {q s L₁ L₂ L₃} : Within (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2*(_root_.Turing.PartrecToTM2.trList L₂).length+6) ⟨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₃)⟩ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList (L₂.headI :: L₁)) [] [] L₃⟩ := by rcases L₂ with - | ⟨a, L₂⟩ · have h : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (1+(2+1+1)) ⟨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₃)⟩ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList ([].headI :: L₁)) [] [] L₃⟩ := by refine steps_trans (move_steps (by decide) (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ [] (some _root_.Turing.PartrecToTM2.Γ'.consₗ) L₃ (by rintro _ ⟨⟩) ⟨rfl,rfl⟩)) (steps_head rfl (steps_head rfl ?_)) rw [_root_.Turing.PartrecToTM2.tr] simp only [_root_.Turing.TM2.stepAux, ite_true, id_eq, _root_.Turing.PartrecToTM2.trList, List.nil_append, elim_update_stack, elim_rev, List.reverseAux_nil, elim_update_rev, Function.update_self, List.headI_nil, _root_.Turing.PartrecToTM2.trNat_default] convert! unrev_steps using 2 <;> simp exact h.within.mono (by simp) · have h : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (((_root_.Turing.PartrecToTM2.trNat a).length+1)+((((_root_.Turing.PartrecToTM2.trList L₂).length+1)+((_root_.Turing.PartrecToTM2.trNat a).length+2)+1)+1)) ⟨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₃)⟩ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList ((a::L₂).headI :: L₁)) [] [] L₃⟩ := by refine steps_trans (move_steps (by decide) (_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₃) (_root_.Turing.PartrecToTM2.trNat_natEnd _) ⟨rfl, by simp⟩)) (steps_head rfl (steps_head rfl ?_)) simp only [_root_.Turing.PartrecToTM2.trList, List.append_assoc, List.cons_append, elim_update_stack, elim_rev, elim_update_rev, Function.update_self, List.headI_cons] refine steps_trans (clear_steps (_root_.Turing.PartrecToTM2.splitAtPred_eq _ _ (_root_.Turing.PartrecToTM2.trList L₂) (some _root_.Turing.PartrecToTM2.Γ'.consₗ) L₃ (fun x h => Bool.decide_false (_root_.Turing.PartrecToTM2.trList_ne_consₗ _ _ h)) ⟨rfl, by simp⟩)) ?_ simpa [List.reverseAux_eq] using (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₃)) exact h.within.mono (by simp only [_root_.Turing.PartrecToTM2.trList, List.length_append, List.length_cons]; omega)
theorem succ_time {q s n} {c d : List _root_.Turing.PartrecToTM2.Γ'} : Within (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2*(_root_.Turing.PartrecToTM2.trNat n).length+2) ⟨some (_root_.Turing.PartrecToTM2.Λ'.succ q), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList [n]) [] c d⟩ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList [n.succ]) [] c d⟩ := by simp only [_root_.Turing.PartrecToTM2.trList, _root_.Turing.PartrecToTM2.trNat.eq_1, Nat.cast_succ, Num.add_one] rcases (n : Num) with - | a · have h : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (1+1) ⟨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⟩ ⟨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 refine steps_head rfl ?_ 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 exact h.within simp only [_root_.Turing.PartrecToTM2.trNum, Num.succ, Num.succ'] have hpref : ∀ l₁, ∃ l₁' l₂' s' t, List.reverseAux l₁ (_root_.Turing.PartrecToTM2.trPosNum a.succ) = List.reverseAux l₁' l₂' ∧ 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⟩ ⟨some (_root_.Turing.PartrecToTM2.unrev q), s', _root_.Turing.PartrecToTM2.K'.elim (l₂' ++ [_root_.Turing.PartrecToTM2.Γ'.cons]) l₁' c d⟩ ∧ t ≤ (_root_.Turing.PartrecToTM2.trPosNum a).length+1 ∧ l₁'.length ≤ l₁.length+(_root_.Turing.PartrecToTM2.trPosNum a).length := by induction a generalizing s with intro l₁ | one => refine ⟨_root_.Turing.PartrecToTM2.Γ'.bit0::l₁, [_root_.Turing.PartrecToTM2.Γ'.bit1], some _root_.Turing.PartrecToTM2.Γ'.cons, 2, rfl, steps_head rfl (steps_one ?_), by simp [_root_.Turing.PartrecToTM2.trPosNum], by simp [_root_.Turing.PartrecToTM2.trPosNum]⟩ simp [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.trPosNum] | bit1 m IH => obtain ⟨l₁',l₂',s',t,e,h,ht,hl⟩ := IH (_root_.Turing.PartrecToTM2.Γ'.bit0::l₁) refine ⟨l₁',l₂',s',t+1,e,steps_head ?_ h,?_,?_⟩ · simp [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.trPosNum] rfl · simp only [_root_.Turing.PartrecToTM2.trPosNum,List.length_cons]; omega · simp only [_root_.Turing.PartrecToTM2.trPosNum,List.length_cons] at *; omega | bit0 m _ => refine ⟨l₁, _, some _root_.Turing.PartrecToTM2.Γ'.bit0, 1, rfl, steps_one ?_, by simp [_root_.Turing.PartrecToTM2.trPosNum], by simp [_root_.Turing.PartrecToTM2.trPosNum]⟩ simp only [_root_.Turing.TM2.step]; rw [_root_.Turing.PartrecToTM2.tr] simp only [_root_.Turing.TM2.stepAux, _root_.Turing.PartrecToTM2.pop', elim_main, elim_update_main, elim_rev, elim_update_rev, Function.update_self] rfl obtain ⟨l₁',l₂',s',t,e,h,ht,hl⟩ := hpref [] simp only [List.reverseAux_nil] at e have hu : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (l₁'.length+1) ⟨some (_root_.Turing.PartrecToTM2.unrev q), s', _root_.Turing.PartrecToTM2.K'.elim (l₂' ++ [_root_.Turing.PartrecToTM2.Γ'.cons]) l₁' c d⟩ ⟨some q, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trPosNum a.succ ++ [_root_.Turing.PartrecToTM2.Γ'.cons]) [] c d⟩ := by convert! unrev_steps using 2 <;> simp [e,List.reverseAux_eq] exact (steps_trans h hu).within.mono (by simp only [List.length_nil, zero_add] at hl; omega)
theorem pred_time (q₁ q₂ s v) (c d : List _root_.Turing.PartrecToTM2.Γ') : ∃ s', Within (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (2*(_root_.Turing.PartrecToTM2.trList v).length+3) ⟨some (_root_.Turing.PartrecToTM2.Λ'.pred q₁ q₂), s, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList v) [] c d⟩ (v.headI.rec ⟨some q₁, s', _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList v.tail) [] c d⟩ fun n _ => ⟨some q₂, s', _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.trList (n::v.tail)) [] c d⟩) := by rcases v with (_ | ⟨_ | n, v⟩) · refine ⟨none, (within_one ?_).mono (by simp)⟩ simp [_root_.Turing.TM2.step] · refine ⟨some _root_.Turing.PartrecToTM2.Γ'.cons, (within_one ?_).mono (by simp)⟩ simp [_root_.Turing.TM2.step] refine ⟨none, ?_⟩ simp only [_root_.Turing.PartrecToTM2.trList, _root_.Turing.PartrecToTM2.trNat.eq_1, _root_.Turing.PartrecToTM2.trNum, Nat.cast_succ, Num.add_one, Num.succ, List.tail_cons, List.headI_cons] rcases (n : Num) with - | a · simp only [_root_.Turing.PartrecToTM2.trPosNum, Num.succ', List.singleton_append, List.nil_append] have h : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (1+1) ⟨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⟩ ⟨some q₂, none, _root_.Turing.PartrecToTM2.K'.elim (_root_.Turing.PartrecToTM2.Γ'.cons::_root_.Turing.PartrecToTM2.trList v) [] c d⟩ := by refine steps_head rfl ?_ rw [_root_.Turing.PartrecToTM2.tr]; simp only [_root_.Turing.PartrecToTM2.pop', _root_.Turing.TM2.stepAux] convert! unrev_steps using 2 <;> simp exact h.within.mono (by simp) simp only [Num.succ'] have hpref : ∀ l₁, ∃ l₁' l₂' s' t, List.reverseAux l₁ (_root_.Turing.PartrecToTM2.trPosNum a) = List.reverseAux l₁' l₂' ∧ Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) t ⟨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⟩ ⟨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⟩ ∧ t ≤ (_root_.Turing.PartrecToTM2.trPosNum a.succ).length+1 ∧ l₁'.length ≤ l₁.length+(_root_.Turing.PartrecToTM2.trPosNum a.succ).length := by induction a generalizing s with intro l₁ | one => refine ⟨_root_.Turing.PartrecToTM2.Γ'.bit1::l₁, [], some _root_.Turing.PartrecToTM2.Γ'.cons, 2, rfl, steps_head rfl (steps_one ?_), by simp [_root_.Turing.PartrecToTM2.trPosNum,PosNum.succ], by simp [_root_.Turing.PartrecToTM2.trPosNum,PosNum.succ]⟩ simp [_root_.Turing.TM2.step, _root_.Turing.PartrecToTM2.trPosNum, show PosNum.one.succ = PosNum.one.bit0 from rfl] | bit1 m IH => obtain ⟨l₁',l₂',s',t,e,h,ht,hl⟩ := IH (some _root_.Turing.PartrecToTM2.Γ'.bit0) (_root_.Turing.PartrecToTM2.Γ'.bit1::l₁) refine ⟨l₁',l₂',s',t+1,e,steps_head ?_ h,?_,?_⟩ · simp [_root_.Turing.TM2.step] rfl · simp only [PosNum.succ,_root_.Turing.PartrecToTM2.trPosNum,List.length_cons]; omega · simp only [PosNum.succ,_root_.Turing.PartrecToTM2.trPosNum,List.length_cons] at *; omega | bit0 m _ => obtain ⟨a,l,e,h⟩ : ∃ a l, _root_.Turing.PartrecToTM2.trPosNum m=a::l ∧ _root_.Turing.PartrecToTM2.natEnd a=false := by cases m <;> refine ⟨_,_,rfl,rfl⟩ refine ⟨_root_.Turing.PartrecToTM2.Γ'.bit0::l₁, _, some a, 1, rfl, steps_one ?_, by simp [PosNum.succ,_root_.Turing.PartrecToTM2.trPosNum], by simp [PosNum.succ,_root_.Turing.PartrecToTM2.trPosNum]⟩ 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, Option.getD,-_root_.Turing.PartrecToTM2.natEnd] simp [_root_.Turing.PartrecToTM2.natEnd] obtain ⟨l₁',l₂',s',t,e,h,ht,hl⟩ := hpref [] simp only [List.reverseAux_nil] at e have hu : Steps (_root_.Turing.TM2.step _root_.Turing.PartrecToTM2.tr) (l₁'.length+1) ⟨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⟩ ⟨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 convert! unrev_steps using 2 <;> simp [e,List.reverseAux_eq] exact (steps_trans h hu).within.mono (by simp only [List.length_nil,zero_add] at hl simp only [List.length_append,List.length_cons]; omega)
end Turing.PartrecToTM2
end
namespace MinUncut.Costed.WordTransduceropen _root_.Turing Function
inductive Tape | input | work | output deriving DecidableEq
protected abbrev Tape.enumList : List Tape := [.input, .work, .output]
protected theorem Tape.enumList_getElem?_ctorIdx_eq (x : Tape) : Tape.enumList[x.ctorIdx]? = some x := by cases x <;> rfl
protected theorem Tape.enumList_nodup : Tape.enumList.Nodup := by decide
instance : Fintype Tape where elems := ⟨Tape.enumList, Tape.enumList_nodup⟩ complete x := by cases x <;> decide
def Alphabet (A B : Type) : Tape → Type | .input => A | .work | .output => B
def tapes {A B : Type} (input : List A) (work output : List B) : ∀ k,List (Alphabet A B k) | .input => input | .work => work | .output => output
@[simp] lemma update_input {A B : Type} (i i' : List A) (w o : List B) : update (tapes i w o) .input i'=tapes i' w o := by funext k cases k <;> simp only [tapes] <;> rfl@[simp] lemma update_work {A B : Type} (i : List A) (w w' o : List B) : update (tapes i w o) .work w'=tapes i w' o := by funext k; cases k <;> rfl@[simp] lemma update_output {A B : Type} (i : List A) (w o o' : List B) : update (tapes i w o) .output o'=tapes i w o' := by funext k; cases k <;> rfl
def pushWord {K Λ σ : Type} {Γ : K → Type} (dst : K) : List (Γ dst) → TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ σ | [], q => q | a::w, q => .push dst (fun _ => a) (pushWord dst w q)
lemma pushWord_aux {K Λ σ : Type} {Γ : K → Type} [DecidableEq K] (dst : K) (w : List (Γ dst)) (q : TM2.Stmt Γ Λ σ) (s : σ) (st : ∀ k,List (Γ k)) : TM2.stepAux (pushWord dst w q) s st= TM2.stepAux q s (update st dst (w.reverse++st dst)) := by induction w generalizing st with | nil => simp [pushWord] | cons a w ih => simp only [pushWord,TM2.stepAux,ih,update_self,update_idem, List.reverse_cons,List.append_assoc,List.singleton_append]
variable {A B Q : Type}inductive Label (Q A : Type) | read | emit (q : Q) (a : A) | reverse deriving DecidableEq, Fintypeabbrev State (Q A B : Type) := Q × Option A × Option B
def output (next : Q → A → Q) (emit : Q → A → List B) : Q → List A → List B | _, [] => [] | q,a::v => emit q a ++ output next emit (next q a) v
def program [Inhabited A] [Inhabited B] (initial : Q) (next : Q → A → Q) (emit : Q → A → List B) : Label Q A → TM2.Stmt (Alphabet A B) (Label Q A) (State Q A B) | .read => .pop .input (fun s a => (s.1,a,s.2.2)) (.branch (fun s => s.2.1.isSome) (.goto fun s => .emit s.1 (s.2.1.getD default)) (.load (fun _ => (initial,none,none)) (.goto fun _ => .reverse))) | .emit q a => .load (fun _ => (next q a,none,none)) (pushWord .work (emit q a) (.goto fun _ => .read)) | .reverse => .pop .work (fun s b => (s.1,s.2.1,b)) (.branch (fun s => s.2.2.isSome) (.push .output (fun s => s.2.2.getD default) (.goto fun _ => .reverse)) (.load (fun _ => (initial,none,none)) .halt))
def machine [Fintype A] [Fintype B] [Fintype Q] [Inhabited A] [Inhabited B] (initial : Q) (next : Q → A → Q) (emit : Q → A → List B) : FinTM2 where K := Tape k₀ := .input k₁ := .output Γ := Alphabet A B Γk₀Fin := inferInstanceAs (Fintype A) Λ := Label Q A main := .read σ := State Q A B initialState := (initial,none,none) m := program initial next emit
lemma finiteAlphabet [Fintype A] [Fintype B] [Fintype Q] [Inhabited A] [Inhabited B] (initial : Q) (next : Q → A → Q) (emit : Q → A → List B) (k : (machine initial next emit).K) : Finite ((machine initial next emit).Γ k) := by cases k <;> dsimp [machine,Alphabet] <;> infer_instance
variable [Inhabited A] [Inhabited B]
lemma reverse_steps (initial : Q) (next : Q → A → Q) (emit : Q → A → List B) (w o : List B) (s : State Q A B) : Steps (TM2.step (program initial next emit)) (w.length+1) ⟨some .reverse,s,tapes [] w o⟩ ⟨none,(initial,none,none),tapes [] [] (w.reverse++o)⟩ := by induction w generalizing s o with | nil => apply steps_one simp only [TM2.step, program] exact congrArg (fun st => (some ⟨none, (initial, none, none), st⟩ : Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B)))) (update_work (A := A) [] [] [] o) | cons b w ih => have h : TM2.step (program initial next emit) ⟨some .reverse,s,tapes [] (b::w) o⟩= some ⟨some .reverse,(s.1,s.2.1,some b),tapes [] w (b::o)⟩ := by have hwork := update_work (A := A) [] (b :: w) w o have hout := update_output (A := A) [] w o (b :: o) have ht := (congrArg (fun st => update st Tape.output (b :: o)) hwork).trans hout exact congrArg (fun st => (some ⟨some .reverse, (s.1, s.2.1, some b), st⟩ : Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B)))) ht simpa only [List.length_cons,List.reverse_cons,List.append_assoc,List.singleton_append] using steps_head h (ih (b::o) (s.1,s.2.1,some b))
lemma emit_steps (initial q : Q) (next : Q → A → Q) (emit : Q → A → List B) (a : A) (v : List A) (w : List B) : Steps (TM2.step (program initial next emit)) 2 ⟨some .read,(q,none,none),tapes (a::v) w []⟩ ⟨some .read,(next q a,none,none),tapes v ((emit q a).reverse++w) []⟩ := by apply steps_head (b := ⟨some (.emit q a),(q,some a,none),tapes v w []⟩) · exact congrArg (fun st => (some ⟨some (.emit q a), (q, some a, none), st⟩ : Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B)))) (update_input (a :: v) v w []) · apply steps_one have hp := pushWord_aux (Γ := Alphabet A B) (Λ := Label Q A) (σ := State Q A B) Tape.work (emit q a) (.goto fun _ => .read) (next q a, none, none) (tapes v w []) exact (congrArg some hp).trans (congrArg (fun st => (some ⟨some .read, (next q a, none, none), st⟩ : Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B)))) (update_work v w ((emit q a).reverse ++ w) []))
lemma read_steps (initial q : Q) (next : Q → A → Q) (emit : Q → A → List B) (v : List A) (w : List B) : Steps (TM2.step (program initial next emit)) (2*v.length+1) ⟨some .read,(q,none,none),tapes v w []⟩ ⟨some .reverse,(initial,none,none),tapes [] ((output next emit q v).reverse++w) []⟩ := by induction v generalizing q w with | nil => apply steps_one exact congrArg (fun st => (some ⟨some .reverse, (initial, none, none), st⟩ : Option (TM2.Cfg (Alphabet A B) (Label Q A) (State Q A B)))) (update_input (A := A) [] [] w []) | cons a v ih => have ht := steps_trans (emit_steps initial q next emit a v w) (ih (next q a) ((emit q a).reverse++w)) convert ht using 1 <;> simp [output,List.reverse_append,List.append_assoc] omega
variable [Fintype A] [Fintype B] [Fintype Q]
def outputsInTime (initial : Q) (next : Q → A → Q) (emit : Q → A → List B) (v : List A) : TM2OutputsInTime (machine initial next emit) v (some (output next emit initial v)) (2*v.length+(output next emit initial v).length+2) := by have h₁ := read_steps initial initial next emit v [] simp only [List.append_nil] at h₁ have h := steps_trans h₁ (reverse_steps initial next emit ((output next emit initial v).reverse) [] (initial,none,none)) have hi : initList (machine initial next emit) v= ⟨some .read,(initial,none,none),tapes v [] []⟩ := by change TM2.Cfg.mk _ _ _=TM2.Cfg.mk _ _ _ congr 1 funext k; cases k <;> rfl have ho : haltList (machine initial next emit) (output next emit initial v)= ⟨none,(initial,none,none),tapes [] [] (output next emit initial v)⟩ := by change TM2.Cfg.mk _ _ _=TM2.Cfg.mk _ _ _ congr 1 funext k; cases k <;> rfl apply steps_timed (n := (2*v.length+1)+((output next emit initial v).reverse.length+1)) · change Steps (TM2.step (program initial next emit)) _ _ _ simp only [hi,ho,List.append_nil,List.reverse_reverse] at h ⊢ exact h · simp only [List.length_reverse]; omega
end MinUncut.Costed.WordTransducer
namespace MinUncut.Costedopen _root_.Turing _root_.Turing.ToPartrec _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Functionopen _root_.Turing.PartrecToTM2.K'
theorem head_tail_length (v : List ℕ) : (trNat v.headI).length+(trList v.tail).length ≤ bitsize v := by cases v <;> simp [bitsize,trList]
theorem head_length (v : List ℕ) : (trNat v.headI).length ≤ bitsize v := (Nat.le_add_right _ _).trans (head_tail_length v)
theorem tail_length (v : List ℕ) : bitsize v.tail ≤ bitsize v := (Nat.le_add_left _ _).trans (head_tail_length v)
theorem save_steps (f fs : Code) (k : Cont') (v : List ℕ) (s : Option Γ') (S : List Γ') : Steps (TM2.step tr) (2*bitsize v+3) ⟨some (trNormal (.cons f fs) k),s,K'.elim (trList v) [] [] S⟩ ⟨some (trNormal f (.cons₁ fs k)),none, K'.elim (trList v) [] [] (trList v ++ Γ'.consₗ::S)⟩ := by have he : 2*bitsize v+3=((trList v).length+1)+((trList v).length+1)+1 := by simp only [bitsize]; omega rw [he] refine steps_head rfl (steps_trans (move_steps (by decide) (splitAtPred_false _)) ?_) simp only [elim_stack,elim_update_stack,elim_update_main,elim_rev,elim_update_rev] simpa [List.reverseAux_eq] using (copy_steps (trNormal f (.cons₁ fs k)) none [] (trList v).reverse [] (Γ'.consₗ::S))
theorem swap_steps (fs : Code) (k : Cont') (v u : List ℕ) (s : Option Γ') (S : List Γ') : Steps (TM2.step tr) (4*bitsize u+2*bitsize v+10) ⟨some (Λ'.ret (.cons₁ fs k)),s, K'.elim (trList u) [] [] (trList v ++ Γ'.consₗ::S)⟩ ⟨some (trNormal fs (.cons₂ k)),none, K'.elim (trList v) [] [] (trList u ++ Γ'.consₗ::S)⟩ := by have he : 4*bitsize u+2*bitsize v+10 = (2*(trList u).length+3)+((2*(trList v).length+3)+(2*(trList u).length+3))+1 := by simp only [bitsize]; omega rw [he] refine steps_head rfl (steps_trans (move₂_steps (by decide) rfl (splitAtPred_false _)) ?_) simp only [Option.elim,id_eq,elim_update_main,elim_aux, List.append_nil,elim_update_aux] refine steps_trans (move₂_steps (o := some Γ'.consₗ) (L₂ := S) (by decide) rfl ?_) ?_ · exact splitAtPred_eq _ _ (trList v) (some Γ'.consₗ) S (fun x h => Bool.decide_false (trList_ne_consₗ _ _ h)) ⟨rfl,rfl⟩ simpa only [Option.elim,List.append_nil,elim_update_stack,elim_main, elim_update_main,id_eq,elim_update_aux,elim_aux,elim_stack] using (move₂_steps (q := trNormal fs (.cons₂ k)) (s := none) (p := fun _ => false) (k₁ := aux) (k₂ := stack) (S := K'.elim (trList v) [] (trList u) (Γ'.consₗ::S)) (by decide) rfl (splitAtPred_false _))
theorem fix_done_steps (f : Code) (k : Cont') (v : List ℕ) (s : Option Γ') (S : List Γ') (hv : v.headI=0) : Steps (TM2.step tr) 1 ⟨some (Λ'.ret (.fix f k)),s,K'.elim (trList v) [] [] S⟩ ⟨some (Λ'.ret k),(trList v).head?,K'.elim (trList v.tail) [] [] S⟩ := by apply steps_one cases v with | nil => simp [TM2.step] | cons a v => simp only [List.headI_cons] at hv subst a simp [TM2.step]
theorem fix_more_steps (f : Code) (k : Cont') (a : ℕ) (v : List ℕ) (s : Option Γ') (S : List Γ') : Steps (TM2.step tr) ((trNat (a+1)).length+1) ⟨some (Λ'.ret (.fix f k)),s,K'.elim (trList ((a+1)::v)) [] [] S⟩ ⟨some (trNormal f (.fix f k)),some Γ'.cons,K'.elim (trList v) [] [] S⟩ := by have htt : natEnd ((trList ((a+1)::v)).head?.getD default)=false ∧ (trList ((a+1)::v)).tail=(trNat (a+1)).tail ++ Γ'.cons::trList v := by simp only [trList,trNat.eq_1,Nat.cast_succ,Num.add_one,Num.succ] cases (a : Num).succ' <;> exact ⟨rfl,rfl⟩ have hn : (trNat (a+1)).length=(trNat (a+1)).tail.length+1 := by simp only [trNat.eq_1,Nat.cast_succ,Num.add_one,Num.succ] cases (a : Num).succ' <;> simp [trNum,trPosNum] rw [hn] refine steps_head rfl ?_ rw [tr]; simp only [TM2.stepAux,pop',elim_main,htt.1] convert! (clear_steps (q := trNormal f (.fix f k)) (s := (trList ((a+1)::v)).head?) (k := main) (S := K'.elim (trList ((a+1)::v)).tail [] [] S) (splitAtPred_eq _ _ (trNat (a+1)).tail (some Γ'.cons) (trList v) (fun x h => trNat_natEnd _ _ (List.tail_subset _ h)) ⟨rfl,htt.2⟩)) using 2 <;> simp
theorem CodeRun.compiled {c v w t} (h : CodeRun c v w t) (k : Cont') (s : Option Γ') (S : List Γ') : ∃ s', Within (TM2.step tr) t ⟨some (trNormal c k),s,K'.elim (trList v) [] [] S⟩ ⟨some (Λ'.ret k),s',K'.elim (trList w) [] [] S⟩ := by induction h generalizing k s S with | zero v => exact ⟨s,within_one (by simp [TM2.step])⟩ | succ v => refine ⟨none,?_⟩ have hh := (head_main_steps (q := Λ'.succ (.ret k)) (s := s) (L := v) (c := []) (d := S)).within.trans (succ_time (n := v.headI)) exact hh.mono (by have hv := head_tail_length v; dsimp [bitsize] at *; omega) | tail v => let o : Option Γ' := List.casesOn v none fun _ _ => some Γ'.cons refine ⟨o,?_⟩ have hh : Steps (TM2.step tr) ((trNat v.headI).length+1) ⟨some (trNormal .tail k),s,K'.elim (trList v) [] [] S⟩ ⟨some (.ret k),o,K'.elim (trList v.tail) [] [] S⟩ := by convert! (clear_steps (q := .ret k) (s := s) (k := main) (S := K'.elim (trList v) [] [] S) (splitAtPred_eq _ _ (trNat v.headI) o (trList v.tail) (trNat_natEnd _) ?_)) using 2 · simp · dsimp [o] cases v <;> exact ⟨rfl,rfl⟩ exact hh.within.mono (by have hv := head_length v; omega) | @cons f fs v u w t t' hf hfs ih ih' => obtain ⟨s₁,h₁⟩ := ih (.cons₁ fs k) none (trList v ++ Γ'.consₗ::S) obtain ⟨s₂,h₂⟩ := ih' (.cons₂ k) none (trList u ++ Γ'.consₗ::S) have h₃ := (save_steps f fs k v s S).within.trans h₁ have h₄ := h₃.trans (swap_steps fs k v u s₁ S).within have h₅ := h₄.trans h₂ have h₆ : Within (TM2.step tr) (2*bitsize u+6+1) ⟨some (.ret (.cons₂ k)),s₂,K'.elim (trList w) [] [] (trList u ++ Γ'.consₗ::S)⟩ ⟨some (.ret k),none,K'.elim (trList (u.headI::w)) [] [] S⟩ := (head_stack_time (q := .ret k) (s := s₂) (L₁ := w) (L₂ := u) (L₃ := S)).head rfl exact ⟨none,(h₅.trans h₆).mono (by omega)⟩ | @comp f g v u w t t' hg hf ih ih' => obtain ⟨s₁,h₁⟩ := ih (.comp f k) s S obtain ⟨s₂,h₂⟩ := ih' k s₁ S exact ⟨s₂,(h₁.trans (h₂.head rfl)).mono (by omega)⟩ | @caseZero f g v w t hz hf ih => obtain ⟨s₁,h₁⟩ := pred_time (trNormal f k) (trNormal g k) s v [] S simp only [hz,Nat.rec_zero] at h₁ obtain ⟨s₂,h₂⟩ := ih k s₁ S exact ⟨s₂,(h₁.trans h₂).mono (by dsimp [bitsize]; omega)⟩ | @caseSucc f g v a w t hg ih => obtain ⟨s₁,h₁⟩ := pred_time (trNormal f k) (trNormal g k) s ((a+1)::v) [] S simp only [List.headI_cons,List.tail_cons] at h₁ obtain ⟨s₂,h₂⟩ := ih k s₁ S exact ⟨s₂,(h₁.trans h₂).mono (by dsimp [bitsize]; omega)⟩ | @fixDone f v u t hf hu ih => obtain ⟨s₁,h₁⟩ := ih (.fix f k) s S exact ⟨(trList u).head?,h₁.trans (fix_done_steps f k u s₁ S hu).within⟩ | @fixMore f v u a w t t' hf hr ih ih' => obtain ⟨s₁,h₁⟩ := ih (.fix f k) s S obtain ⟨s₂,h₂⟩ := ih' k (some Γ'.cons) S exact ⟨s₂,((h₁.trans (fix_more_steps f k a u s₁ S).within).trans h₂).mono (by dsimp [bitsize]; simp only [List.length_append,List.length_cons]; omega)⟩
open _root_.Turingnamespace FiniteControlvariable {K Λ σ : Type} {Γ : K → Type} [DecidableEq K]
noncomputable def stmt (S : Finset Λ) : (q : TM2.Stmt Γ Λ σ) → TM2.SupportsStmt S q → TM2.Stmt Γ S σ | .push k f q, h => .push k f (stmt S q h) | .peek k f q, h => .peek k f (stmt S q h) | .pop k f q, h => .pop k f (stmt S q h) | .load f q, h => .load f (stmt S q h) | .branch f q r, h => .branch f (stmt S q h.1) (stmt S r h.2) | .goto f, h => .goto (fun s => ⟨f s,h s⟩) | .halt, _ => .halt
def project (S : Finset Λ) (c : TM2.Cfg Γ S σ) : TM2.Cfg Γ Λ σ := ⟨c.l.map Subtype.val,c.var,c.stk⟩
omit [DecidableEq K] inlemma project_injective (S : Finset Λ) : Function.Injective (project (Γ:=Γ) (σ:=σ) S) := by intro a b h cases a with | mk a v A => cases b with | mk b w B => simp only [project,TM2.Cfg.mk.injEq] at h rcases h with ⟨h,hv,hB⟩ have hab : a=b := Option.map_injective Subtype.val_injective h cases hab; cases hv; cases hB; rfl
lemma project_aux (S : Finset Λ) (q : TM2.Stmt Γ Λ σ) (h : TM2.SupportsStmt S q) (s : σ) (st : ∀ k,List (Γ k)) : project S (TM2.stepAux (stmt S q h) s st)=TM2.stepAux q s st := by induction q generalizing s st with | push k f q ih => exact ih h _ _ | peek k f q ih => exact ih h _ _ | pop k f q ih => exact ih h _ _ | load f q ih => exact ih h _ _ | branch f q r ih ih' => cases he : f s <;> simp only [stmt,TM2.stepAux,he, Bool.cond_false,Bool.cond_true] <;> first | exact ih h.1 _ _ | exact ih' h.2 _ _ | goto f => rfl | halt => rfl
noncomputable def program (S : Finset Λ) (m : Λ → TM2.Stmt Γ Λ σ) (h : ∀q∈S,TM2.SupportsStmt S (m q)) : S → TM2.Stmt Γ S σ := fun q => stmt S (m q.val) (h q q.property)
lemma project_step (S : Finset Λ) (m : Λ → TM2.Stmt Γ Λ σ) (h : ∀q∈S,TM2.SupportsStmt S (m q)) (c : TM2.Cfg Γ S σ) : (TM2.step (program S m h) c).map (project S)=TM2.step m (project S c) := by rcases c with ⟨l,s,st⟩ cases l with | none => rfl | some q => exact congrArg some (project_aux S (m q) (h q q.property) s st)
lemma projected_iterate {α β : Type} (f : α → Option α) (g : β → Option β) (p : α → β) (h : ∀a,(f a).map p=g (p a)) (n : ℕ) (a : Option α) : ((fun x => x.bind f)^[n] a).map p=(fun x => x.bind g)^[n] (a.map p) := by induction n generalizing a with | zero => rfl | succ n ih => rw [Function.iterate_succ_apply,Function.iterate_succ_apply,ih] congr 1 cases a with | none => rfl | some a => exact h a
end FiniteControlend MinUncut.Costed
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import Mathlibimport OAI.Computability.MinUncut.Analysis.LiteralGaussian
namespace OAI
sectionnoncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheorynamespace MinUncut.FiniteGaussianopen GaussianBudget MinUncut.Innerattribute [local instance] Classical.propDecidablevariable {m n : ℕ}
def sourceTable (σ η : ℝ) (c g : Point m n → ℝ) (l : Code m n → ℝ) : ScoreIndex m n → Bool := fun s => if s.1 then query (c+σ•g) (η•l) s.2 else query c 0 s.2
lemma sourceTable_packed (σ η : ℝ) (c g : Point m n → ℝ) (l : Code m n → ℝ) : sourceTable σ η c g l=thresholdTable (scoreFamily σ η) (packEquiv (c,g,l)) := by funext s exact (scoreFamily_packed σ η s (c,g,l)).symm
lemma table_integral_pack (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ) (hF : ∀ t, 0≤F t ∧ F t≤1) : (∫ c, ∫ g, ∫ l, F (sourceTable σ η c g l) ∂gauss (Code m n) ∂gauss (Point m n) ∂gauss (Point m n))= ∫ x, F (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) := by have ht := tableTest_integrable (scoreFamily σ η) F hF have hp := pack_preserving (X := Point m n) (C := Code m n) have hi : Integrable (fun p : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) => F (thresholdTable (scoreFamily σ η) (packEquiv p))) (productLaw (Point m n) (Code m n)) := hp.integrable_comp_of_integrable ht rw [← hp.integral_comp packEquiv.measurableEmbedding (fun x => F (thresholdTable (scoreFamily σ η) x))] rw [integral_prod _ hi] apply integral_congr_ae filter_upwards [hi.prod_right_ae] with c hc rw [integral_prod _ hc] apply integral_congr_ae filter_upwards [] with g apply integral_congr_ae filter_upwards [] with l rw [sourceTable_packed]
lemma sourceTest_integrable (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ) (hF : ∀ t, 0≤F t ∧ F t≤1) : Integrable (fun p : (Point m n → ℝ) × ((Point m n → ℝ) × (Code m n → ℝ)) => F (sourceTable σ η p.1 p.2.1 p.2.2)) (productLaw (Point m n) (Code m n)) := by simp_rw [sourceTable_packed] exact (pack_preserving (X := Point m n) (C := Code m n)).integrable_comp_of_integrable (tableTest_integrable (scoreFamily σ η) F hF)
lemma sourceTest_inner_integrable (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ) (hF : ∀ t, 0≤F t ∧ F t≤1) (c : Point m n → ℝ) : Integrable (fun p : (Point m n → ℝ) × (Code m n → ℝ) => F (sourceTable σ η c p.1 p.2)) ((gauss (Point m n)).prod (gauss (Code m n))) := by simp_rw [sourceTable_packed] apply Integrable.of_bound (((measurable_of_countable F).comp (thresholdTable_measurable (scoreFamily σ η))).comp (packEquiv.measurable.comp (measurable_const.prodMk measurable_id))).aestronglyMeasurable 1 filter_upwards [] with p simpa only [Function.comp_apply,id_eq,Real.norm_eq_abs,abs_of_nonneg (hF _).1] using (hF (thresholdTable (scoreFamily σ η) (packEquiv (c,p)))).2
lemma sourceTest_outer_integrable (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ) (hF : ∀ t, 0≤F t ∧ F t≤1) : Integrable (fun c => ∫ g, ∫ l, F (sourceTable σ η c g l) ∂gauss (Code m n) ∂gauss (Point m n)) (gauss (Point m n)) := by have hi := (sourceTest_integrable σ η F hF).integral_prod_left have he (c : Point m n → ℝ) := integral_prod (fun p : (Point m n → ℝ) × (Code m n → ℝ) => F (sourceTable σ η c p.1 p.2)) (sourceTest_inner_integrable σ η F hF c) change Integrable (fun c => ∫ p : (Point m n → ℝ) × (Code m n → ℝ), F (sourceTable σ η c p.1 p.2) ∂(gauss (Point m n)).prod (gauss (Code m n))) (gauss (Point m n)) at hi simpa only [he] using hi
lemma table_integral_product (σ η : ℝ) (F : (ScoreIndex m n → Bool) → ℝ) (hF : ∀ t, 0≤F t ∧ F t≤1) : (∫ c, ∫ p : (Point m n → ℝ) × (Code m n → ℝ), F (sourceTable σ η c p.1 p.2) ∂(gauss (Point m n)).prod (gauss (Code m n)) ∂gauss (Point m n))= ∫ x, F (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) := by rw [← table_integral_pack σ η F hF] apply integral_congr_ae filter_upwards [] with c exact integral_prod _ (sourceTest_inner_integrable σ η F hF c)
end MinUncut.FiniteGaussian
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import Mathlibimport OAI.Computability.MinUncut.Estimates.ActualBoxBoundimport OAI.Computability.MinUncut.Estimates.FourthTestimport OAI.Computability.MinUncut.Estimates.TableLawPacking
namespace OAI
sectionnoncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheorynamespace MinUncut.FiniteGaussianopen GaussianBudget MinUncut.Innerattribute [local instance] Classical.propDecidablevariable {V A V' A' : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] [AddCommGroup V'] [Module F₂ V'] [AddTorsor V' A'] [Fintype A'] {m n : ℕ}
def disagreement (b c : Bool) : ℝ := if b=c then 0 else 1
lemma disagreement_range (b c : Bool) : 0≤disagreement b c ∧ disagreement b c≤1 := by unfold disagreement split <;> norm_num
def firstTable (f : FoldedProof A) (B : FaceArray A m n) (t : ScoreIndex m n → Bool) : ℝ := disagreement (f.answer (fun a => t (false,labelCode B a))) (f.answer (fun a => t (true,labelCode B a)))
def secondTable (f : FoldedProof A) (B C : FaceArray A m n) (t : ScoreIndex m n → Bool) : ℝ := disagreement (f.answer (fun a => t (true,labelCode B a))) (f.answer (fun a => t (true,labelCode C a)))
def thirdTable (f : FoldedProof A) (B : FaceArray A m n) (z : Code m n) (t : ScoreIndex m n → Bool) : ℝ := disagreement (f.answer (fun a => Function.update (fun z => t (true,z)) z true (labelCode B a))) (f.answer (fun a => Function.update (fun z => t (true,z)) z false (labelCode B a)))
def fourthTable (f : FoldedProof A) (g : FoldedProof A') (B : FaceArray A m n) (C : FaceArray A' m n) (t : ScoreIndex m n → Bool) : ℝ := disagreement (f.answer (fun a => t (true,labelCode B a))) (g.answer (fun a => t (true,labelCode C a)))
omit [Fintype A] inlemma firstTable_source (f : FoldedProof A) (B : FaceArray A m n) (σ η : ℝ) (c g : Point m n → ℝ) (l : Code m n → ℝ) : firstTable f B (sourceTable σ η c g l)=firstFailure f B σ η c g l := rfl
omit [Fintype A] inlemma secondTable_source (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) (c g : Point m n → ℝ) (l : Code m n → ℝ) : secondTable f B C (sourceTable σ η c g l)=secondFailure f B C σ η c (g,l) := rfl
omit [Fintype A] inlemma thirdTable_source (f : FoldedProof A) (B : FaceArray A m n) (σ η : ℝ) (c g : Point m n → ℝ) (l : Code m n → ℝ) (z : Code m n) : thirdTable f B z (sourceTable σ η c g l)=thirdFailure f B η (c+σ•g) l z := rfl
omit [Fintype A] [Fintype A'] inlemma fourthTable_source (f : FoldedProof A) (g : FoldedProof A') (B : FaceArray A m n) (C : FaceArray A' m n) (σ η : ℝ) (c h : Point m n → ℝ) (l : Code m n → ℝ) : fourthTable f g B C (sourceTable σ η c h l)=comparisonFailure f g B C σ η c (h,l) := rfl
omit [Fintype A] inlemma firstTable_integral (f : FoldedProof A) (B : FaceArray A m n) (σ η : ℝ) : (∫ c, firstRejection f B σ η c ∂gauss (Point m n))= ∫ x, firstTable f B (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) := table_integral_pack σ η (firstTable f B) (fun _ => disagreement_range _ _)
omit [Fintype A] inlemma secondTable_integral (f : FoldedProof A) (B C : FaceArray A m n) (σ η : ℝ) : (∫ c, secondRejection f B C σ η c ∂gauss (Point m n))= ∫ x, secondTable f B C (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) := table_integral_product σ η (secondTable f B C) (fun _ => disagreement_range _ _)
omit [Fintype A] inlemma thirdTable_integral (f : FoldedProof A) (B : FaceArray A m n) (σ η : ℝ) : (∫ c, thirdRejection f B σ η c ∂gauss (Point m n))= 𝔼 z : Code m n, ∫ x, thirdTable f B z (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) := by unfold thirdRejection simp only [Fintype.expect_eq_sum_div_card,integral_div] simp_rw [← thirdTable_source] rw [integral_finsetSum _ (fun z _ => sourceTest_outer_integrable σ η (thirdTable f B z) (fun _ => disagreement_range _ _))] congr 1 apply Finset.sum_congr rfl intro z _ exact table_integral_pack σ η (thirdTable f B z) (fun _ => disagreement_range _ _)
omit [Fintype A] [Fintype A'] inlemma fourthTable_integral (f : FoldedProof A) (g : FoldedProof A') (B : FaceArray A m n) (C : FaceArray A' m n) (σ η : ℝ) : (∫ c, comparisonRejection f g B C σ η c ∂gauss (Point m n))= ∫ x, fourthTable f g B C (thresholdTable (scoreFamily σ η) x) ∂gaussianLaw (TestCoordinates m n) := table_integral_product σ η (fourthTable f g B C) (fun _ => disagreement_range _ _)
end MinUncut.FiniteGaussian
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376import Mathlibimport OAI.Computability.MinUncut.Search.UniformQuantifierimport OAI.Computability.MinUncut.Estimates.UniformTransportimport OAI.Computability.MinUncut.Encoding.SignatureEncodingimport OAI.Computability.MinUncut.Search.TemplateArithmetic
namespace OAI
sectionnamespace MinUncut.SourceTemplateopen MinUncutGames.Foundations MinUncutGames.Foundations.Targetopen PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrencesopen MinUncutGames.Reduction.CloneGapopen MinUncut.Costedopen scoped BigOperators
def functionExpr {A : Type} (e : Encoding A) (b : ℕ) (f : A → AExpr) : AExpr := AExpr.sum (List.ofFn (fun i : Fin e.size => .mul (f (e.code.symm i)) (.const (b^i.val))))
lemma functionExpr_eval {A B : Type} (a : Encoding A) (b : Encoding B) (f : A → AExpr) (g : A → B) (v : List ℕ) (h : ∀x,(f x).eval v=(b.code (g x)).val) : (functionExpr a b.size f).eval v=((a.function b).code g).val := by simp only [functionExpr,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn,AExpr.eval,h] rfl
def positiveExpr (u : ℕ) : AExpr := functionExpr (Encoding.fin u) (2^3) (fun i => functionExpr slotEncoding 2 (fun s=>slotWord i.val s 1))def sameExpr (u : ℕ) : AExpr := functionExpr (coordinateEncoding u) (2^(u*3)) (fun a => functionExpr (coordinateEncoding u) 2 (fun b=>.eq (slotWord a.1.val a.2 0) (slotWord b.1.val b.2 0)))def signatureExpr (u : ℕ) : AExpr := .add (sameExpr u) (.mul (.const ((2^(u*3))^(u*3))) (positiveExpr u))
lemma positiveExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) : (positiveExpr u).eval (inputTuple F c)= ((((Encoding.fin u).function (slotEncoding.function Encoding.bool)).code (signature F c).positive)).val := by unfold positiveExpr apply functionExpr_eval (Encoding.fin u) (slotEncoding.function Encoding.bool) intro i apply functionExpr_eval slotEncoding Encoding.bool intro s rw [slotWord_positive,MinUncut.Outer.LocalTemplate.bool_code] rfl
lemma sameExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) : (sameExpr u).eval (inputTuple F c)= ((((coordinateEncoding u).function ((coordinateEncoding u).function Encoding.bool)).code (signature F c).same)).val := by unfold sameExpr apply functionExpr_eval (coordinateEncoding u) ((coordinateEncoding u).function Encoding.bool) intro a apply functionExpr_eval (coordinateEncoding u) Encoding.bool intro b simp only [AExpr.eval,slotWord_name,signature,MinUncut.Outer.LocalTemplate.bool_code] by_cases h : nameAt (clauseAt F (c a.1)) a.2=nameAt (clauseAt F (c b.1)) b.2 · simp only [h,ite_true,decide_true,Bool.toNat_true] · have hh := Fin.val_ne_of_ne h simp only [hh,ite_false,h,decide_false,Bool.toNat_false]
lemma signatureExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) : (signatureExpr u).eval (inputTuple F c)=((signatureEncoding u).code (signature F c)).val := by simp only [signatureExpr,AExpr.eval,positiveExpr_eval,sameExpr_eval] rfl
def signatureLookup {u : ℕ} (f : Signature u → ℕ) : AExpr := (signatureExpr u).lookup (MinUncut.Outer.LocalTemplate.constantTable (signatureEncoding u) f)
lemma signatureLookup_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) (f : Signature u → ℕ) : (signatureLookup f).eval (inputTuple F c)=f (signature F c) := by apply MinUncut.Outer.LocalTemplate.constantTable_eval exact signatureExpr_eval F c
def sampledExpr {u : ℕ} (s : SlotContext u) : AExpr := AExpr.sum (List.ofFn (fun i : Fin u=>.mul (slotWord i.val (s i) 0) ((AExpr.reg 1).pow i.val)))
lemma sampledExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) (s : SlotContext u) : (sampledExpr s).eval (inputTuple F c)= ((variableEncoding F u).code (sampledVariables F c s)).val := by simp only [sampledExpr,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn,AExpr.eval, AExpr.eval_pow,slotWord_name] rfl
def addressExpr {u : ℕ} (s : SlotContext u) (f : Signature u → LocalKey u) : AExpr := let tag := signatureLookup (fun S=>keyTag (f S)) let table := signatureLookup (fun S=>keyTable (f S)) let leftSize := .mul ((AExpr.reg 1).pow u) (.const (2^(2^u))) .cond (.eq tag (.const 0)) (.cond (.eq tag (.const 1)) (.add leftSize (.mul ((AExpr.reg 2).pow u) (.const (2^(8^u))))) (.add leftSize (.add table (.mul (.const (2^(8^u))) (.reg 0))))) (.add table (.mul (.const (2^(2^u))) (sampledExpr s)))
lemma addressExpr_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) (s : SlotContext u) (f : Signature u → LocalKey u) : (addressExpr s f).eval (inputTuple F c)= (keyAddress F c (sampledVariables F c s) (f (signature F c))).val := by rw [keyAddress_number] simp only [addressExpr,AExpr.eval,signatureLookup_eval,sampledExpr_eval,AExpr.eval_pow] by_cases h0 : keyTag (f (signature F c))=0 · simp only [h0,ite_true,Nat.one_ne_zero,ite_false,keyNumber] · by_cases h1 : keyTag (f (signature F c))=1 <;> simp only [h0,h1,ite_true,ite_false,Nat.one_ne_zero,keyNumber,inputTuple, Complexity.formulaWords,List.cons_append,List.nil_append,List.drop_succ_cons, List.drop_zero,List.headI_cons]
def equationExpressions {u D : ℕ} (s : SlotContext u) (t : SourceTape.TestTape (I u) (J u) D) : List AExpr := [addressExpr s (fun S=>(S.equation s t).first), addressExpr s (fun S=>(S.equation s t).second), addressExpr s (fun S=>(S.equation s t).third), signatureLookup (fun S=>(S.equation s t).rhs.toNat)]
lemma equationExpressions_eval (F : Formula) {u D : ℕ} (c : ClauseContext F u) (s : SlotContext u) (t : SourceTape.TestTape (I u) (J u) D) : (equationExpressions s t).map (fun e=>e.eval (inputTuple F c))= MinUncutGames.Reduction.SourceEncoding.equationWords (sourceEquation F u D ((c,s),t)) := by rw [←signature_equation] simp only [equationExpressions,List.map_cons,List.map_nil,addressExpr_eval,signatureLookup_eval] unfold mapEquation MinUncutGames.Reduction.SourceEncoding.equationWords congr 3 cases ((signature F c).equation s t).rhs <;> rfl
end MinUncut.SourceTemplate
endsectionnoncomputable sectionnamespace MinUncut.Preprocess.Syntaxopen MinUncutGames.Foundations.Hastad.SourceOccurrencesopen MinUncut.FiniteProof MinUncut.Costed MinUncut.CodeEffective Turing.ToPartrec UEncodingvariable {P : Type} [Primcodable P] {A B : P → Type} {c : UEncoding P A}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 := Out.ofEq hf (fun p x=>congrArg (fun a:AExpr=>a.program.code) (h p x))
def eqCode (a b : Code) : Code := branch (bin PolyProgram.add.code (bin PolyProgram.sub.code a b) (bin PolyProgram.sub.code b a)) (constCode 1) (constCode 0)lemma p_eqCode : Primrec₂ eqCode := p_branch.comp (((p_bin _).comp ((p_bin _).comp Primrec.fst Primrec.snd) ((p_bin _).comp Primrec.snd Primrec.fst)).pair ((Primrec.const (constCode 1)).pair (Primrec.const (constCode 0))))def lookupCode (a : Code) (xs : List (ℕ × ℕ)) : Code := xs.foldr (fun ix b=>branch (eqCode a (constCode ix.1)) b (constCode ix.2)) (constCode 0)lemma p_lookupCode : Primrec₂ lookupCode := by exact Primrec.list_foldr Primrec.snd (Primrec.const (constCode 0)) (p_branch.comp ((p_eqCode.comp (Primrec.fst.comp Primrec.fst) (p_constCode.comp (Primrec.fst.comp (Primrec.fst.comp Primrec.snd)))).pair (Primrec.snd.comp Primrec.snd |>.pair (p_constCode.comp (Primrec.snd.comp (Primrec.fst.comp Primrec.snd)))))).to₂lemma lookupCode_eq (a : AExpr) (xs : List (ℕ × ℕ)) : lookupCode a.program.code xs=(a.lookup xs).program.code := by induction xs with | nil => rfl | cons ix xs ih => simp only [lookupCode,List.foldr_cons] at * rw [ih] rw [AExpr.lookup,cond_code,eq_code] rfllemma O.lookup {a : ∀p,A p → AExpr} {xs : ∀p,A p → List (ℕ × ℕ)} (ha : O c a) (hx : c.Out xs) : O c (fun p x=>(a p x).lookup (xs p x)) := (ha.map₂ hx p_lookupCode.to_comp).ofEq (fun p x=>lookupCode_eq (a p x) (xs p x))lemma O.sum_enum {b : UEncoding P B} {f : ∀p,A p × B p → AExpr} (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 apply O.sum apply (out_list hf).ofEq intro p x simp only [List.map_map,Function.comp_def]lemma O.sum_fin {n : P → ℕ} (hn : Computable n) {f : ∀p,A p × Fin (n p) → AExpr} (hf : O (c.prod (fin n hn)) f) : O c (fun p x=>AExpr.sum (List.ofFn (fun i=>f p (x,i)))) := by apply hf.sum_enum.ofEq intro p x simp only [fin,Encoding.fin,Encoding.enumerate,List.map_ofFn,Function.comp_def,Equiv.refl_symm] rfllemma out_constantTable {b : UEncoding P B} {f : ∀p,A p × B p → ℕ} (hf : (c.prod b).Out f) : c.Out (fun p x=>MinUncut.Outer.LocalTemplate.constantTable (b.enc p) (fun y=>f p (x,y))) := out_list ((out_code b).second.pair hf)lemma O.functionExpr {b : UEncoding P B} {base : P → ℕ} (hb : Computable base) {f : ∀p,A p × B p → AExpr} (hf : O (c.prod b) f) : O c (fun p x=>MinUncut.SourceTemplate.functionExpr (b.enc p) (base p) (fun y=>f p (x,y))) := by have hpow : (c.prod b).Out (fun p x=>base p ^ ((b.enc p).code x.2).val) := (out_const _ hb).map₂ (out_code b).second (ca_pow Computable.fst Computable.snd) apply (hf.mul (O.const hpow)).sum_enum.ofEq intro p x simp only [MinUncut.SourceTemplate.functionExpr,Encoding.enumerate,List.map_ofFn,Function.comp_def,Equiv.apply_symm_apply]end MinUncut.Preprocess.Syntax
endendsectionnamespace MinUncut.Preprocess.Sourceopen MinUncutGames.Foundations MinUncutGames.Foundations.Targetopen PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrencesopen MinUncut.SourceTemplate UEncoding
def positions : UEncoding ℕ Fin := UEncoding.fin id Computable.iddef slots : UEncoding ℕ (fun _=>Slot) := fixed slotEncodingdef answers : UEncoding ℕ (fun _=>ClauseAnswer) := fixed clauseAnswerEncodingdef lefts : UEncoding ℕ I := positions.function booldef rights : UEncoding ℕ J := positions.function answersdef coordinates : UEncoding ℕ (fun u=>Fin u × Slot) := positions.prod slotsdef polarities : UEncoding ℕ (fun u=>Fin u → Slot → Bool) := positions.function (slots.function bool)def equalities : UEncoding ℕ (fun u=>(Fin u × Slot) → (Fin u × Slot) → Bool) := coordinates.function (coordinates.function bool)def signatures : UEncoding ℕ Signature := (polarities.prod equalities).ofEquiv signatureEquiv
lemma signatures_encoding (u : ℕ) : signatures.enc u=signatureEncoding u := rfllemma map_positive : signatures.Map polarities (fun _ s=>s.positive) := by change ((polarities.prod equalities).ofEquiv signatureEquiv).Map polarities (fun u s=>(signatureEquiv u s).1) exact map_comp (map_to (polarities.prod equalities) signatureEquiv) (map_fst polarities equalities)lemma map_same : signatures.Map equalities (fun _ s=>s.same) := by change ((polarities.prod equalities).ofEquiv signatureEquiv).Map equalities (fun u s=>(signatureEquiv u s).2) exact map_comp (map_to (polarities.prod equalities) signatureEquiv) (map_snd polarities equalities)
variable {Γ : ℕ → Type} {g : UEncoding ℕ Γ}lemma map_satisfies {s : ∀u,Γ u → Signature u} {j : ∀u,Γ u → J u} {t : ∀u,Γ u → Fin u} (hs : g.Map signatures s) (hj : g.Map rights j) (ht : g.Map positions t) : g.Map bool (fun u x=>(s u x).satisfies (j u x) (t u x)) := by exact map_binary (slotEncoding.function Encoding.bool) clauseAnswerEncoding Encoding.bool (fun p a=>(literalValue (p .first) a.first || literalValue (p .second) a.second) || literalValue (p .third) a.third) (map_apply (map_comp hs map_positive) ht) (map_apply hj ht)
lemma map_same_at {s : ∀u,Γ u → Signature u} {a b : ∀u,Γ u → Fin u × Slot} (hs : g.Map signatures s) (ha : g.Map coordinates a) (hb : g.Map coordinates b) : g.Map bool (fun u x=>(s u x).same (a u x) (b u x)) := map_apply (map_apply (map_comp hs map_same) ha) hblemma map_answer_at {j : ∀u,Γ u → J u} {a : ∀u,Γ u → Fin u × Slot} (hj : g.Map rights j) (ha : g.Map coordinates a) : g.Map bool (fun u x=>answerAt (j u x (a u x).1) (a u x).2) := map_binary clauseAnswerEncoding slotEncoding Encoding.bool answerAt (map_apply hj (map_comp ha (map_fst _ _))) (map_comp ha (map_snd _ _))
lemma map_consistent {s : ∀u,Γ u → Signature u} {j : ∀u,Γ u → J u} {a b : ∀u,Γ u → Fin u × Slot} (hs : g.Map signatures s) (hj : g.Map rights j) (ha : g.Map coordinates a) (hb : g.Map coordinates b) : g.Map bool (fun u x=>decide ((s u x).same (a u x) (b u x)=true → 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 apply (map_or (map_not (map_same_at hs ha hb)) (map_bool_eq (map_answer_at hj ha) (map_answer_at hj hb))).ofEq intro u x by_cases h:(s u x).same (a u x) (b u x)=true <;> simp [h]
lemma map_valid : (signatures.prod rights).Map bool (fun _ x=>x.1.valid x.2) := by classical have hs : ((signatures.prod rights).prod positions).Map bool (fun u x=>x.1.1.satisfies x.1.2 x.2) := map_satisfies (map_fst signatures rights).first (map_snd signatures rights).first (map_snd _ _) have hc : (((signatures.prod rights).prod coordinates).prod coordinates).Map bool (fun u x=>decide (x.1.1.1.same x.1.2 x.2=true → answerAt (x.1.1.2 x.1.2.1) x.1.2.2=answerAt (x.1.1.2 x.2.1) x.2.2)) := map_consistent (map_fst signatures rights).first.first (map_snd signatures rights).first.first (map_snd (signatures.prod rights) coordinates).first (map_snd _ _) apply (map_and (map_forall hs) (map_forall (map_forall hc))).ofEq intro u x simp only [Signature.valid,Bool.decide_and,decide_eq_true_eq] congr 1 apply decide_eq_decide.mpr simp only [Prod.forall] constructor · intro h t t' s s' he exact h t s t' s' he · intro h t s t' s' he exact h t t' s s' he
end MinUncut.Preprocess.Source
endsectionnamespace MinUncut.Preprocess.Sourceopen MinUncutGames.Foundations MinUncutGames.Foundations.Targetopen PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrencesopen MinUncut.SourceTemplate UEncoding
def slotContexts : UEncoding ℕ SlotContext := positions.function slots
variable {Γ : ℕ → Type} {g : UEncoding ℕ Γ}lemma map_slot {s : ∀u,Γ u → Signature u} {r : ∀u,Γ u → SlotContext u} {t : ∀u,Γ u → Fin u} (hs : g.Map signatures s) (hr : g.Map slotContexts r) (ht : g.Map positions t) : g.Map slots (fun u x=>(s u x).slot (r u x) (t u x)) := by exact map_binary Encoding.bool Encoding.bool slotEncoding (fun b c=>if b then .first else if c then .second else .third) (map_same_at hs (map_pair ht (map_const (Computable.const 0))) (map_pair ht (map_apply hr ht))) (map_same_at hs (map_pair ht (map_const (Computable.const 1))) (map_pair ht (map_apply hr ht)))
lemma map_project {s : ∀u,Γ u → Signature u} {r : ∀u,Γ u → SlotContext u} {j : ∀u,Γ u → J u} (hs : g.Map signatures s) (hr : g.Map slotContexts r) (hj : g.Map rights j) : g.Map lefts (fun u x=>(s u x).project (r u x) (j u x)) := by exact map_lambda (map_binary clauseAnswerEncoding slotEncoding Encoding.bool answerAt (map_apply hj.first (map_snd g positions)) (map_slot hs.first hr.first (map_snd g positions)))
lemma map_anchor (a : UEncoding ℕ Γ) : a.Map lefts (fun u _=>leftAnchor u) := map_lambda (map_false (a.prod positions))
end MinUncut.Preprocess.Source
namespace MinUncut.Preprocess.UEncodingopen MinUncutGames.Foundations.Hastad.SourceOccurrencesopen MinUncutGames.Foundations.Hastadvariable {P : Type} [Primcodable P] {A Γ : P → Type}lemma map_xor {g : UEncoding P Γ} {f h : ∀p,Γ p → Bool} (hf : g.Map bool f) (hh : g.Map bool h) : g.Map bool (fun p x=>f p x ^^ h p x) := map_binary Encoding.bool Encoding.bool Encoding.bool Bool.xor hf hh
lemma map_representative {g : UEncoding P Γ} {a : UEncoding P A} {f : ∀p,Γ p → A p → Bool} {i : ∀p,Γ p → A p} (hf : g.Map (a.function bool) f) (hi : g.Map a i) : g.Map (a.function bool) (fun p x=>representative (i p x) (f p x)) := by apply (map_lambda (map_xor (map_apply hf.first (map_snd g a)) (map_apply hf hi).first)).ofEq intro p x funext y 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 cases f p x (i p x) <;> simp [cubeFlip]end MinUncut.Preprocess.UEncoding
endsectionnamespace MinUncut.SourceTemplateopen MinUncutGames.Foundations MinUncutGames.Foundations.Targetopen PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrencesopen MinUncutGames.Reduction.CloneGap
def paddedRep {u : ℕ} (valid : J u → Bool) (j₀ : J u) (g : Cube (J u)) : Cube (J u) := fun j=>if valid j then representative j₀ g j else false
lemma extend_representative {u : ℕ} (valid : J u → Bool) (j₀ : {j : J u // valid j=true}) (g : Cube (J u)) : extendRestricted valid (representative j₀ (restrictQuery valid g))=paddedRep valid j₀ g := by funext j unfold extendRestricted paddedRep by_cases h:valid j=true · simp only [h,↓reduceDIte,ite_true] cases h₀:g j₀ <;> simp [representative,restrictQuery,cubeFlip,h₀] · simp [h]
lemma findValid_map {X : Type} (valid : X → Bool) (xs : List X) : (findValid valid xs).map Subtype.val=xs.find? valid := by induction xs with | nil => rfl | cons x xs ih => by_cases h:valid x=true <;> simp [findValid,h,ih]
def rawLocal {u : ℕ} (valid : J u → Bool) (π : J u → I u) (f : Cube (I u)) (g μ : Cube (J u)) : Equation (LocalKey u) := ((jEncoding u).enumerate.find? valid).elim ⟨.inl (representative (leftAnchor u) f),.inr (.inr ()),.inr (.inr ()),f (leftAnchor u)⟩ (fun j₀=>⟨.inl (representative (leftAnchor u) f), .inr (.inl (paddedRep valid j₀ g)), .inr (.inl (paddedRep valid j₀ (thirdQuery π f g μ))), f (leftAnchor u) ^^ f (π j₀) ^^ μ j₀⟩)
lemma rawLocal_eq {u D : ℕ} (valid : J u → Bool) (π : J u → I u) (t : SourceTape.TestTape (I u) (J u) D) : rawLocal valid π t.1 t.2.2 (MinUncutGames.Reduction.FiniteNoise.realizedNoise t.2.1)= localEquation valid π t := by rw [rawLocal,←findValid_map,←firstValid] unfold localEquation cases hh:firstValid (jEncoding u) valid with | none => rfl | some j₀ => dsimp only [Option.map_some,Option.elim_some,mapEquation,FoldedEquation.conditionedEquation, FoldedEquation.equation,foldedLocal,canonicalInput] rw [extend_representative] have he : thirdQuery (fun j:{j : J u // valid j=true}=>π j.val) t.1 (restrictQuery valid t.2.2) (restrictQuery valid (MinUncutGames.Reduction.FiniteNoise.realizedNoise t.2.1))= restrictQuery valid (thirdQuery π t.1 t.2.2 (MinUncutGames.Reduction.FiniteNoise.realizedNoise t.2.1)) := rfl rw [he,extend_representative] rflend MinUncut.SourceTemplate
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import Mathlibimport OAI.Computability.MinUncut.Estimates.UniformTransportimport OAI.Computability.MinUncut.Estimates.UniformRestrictimport OAI.Computability.MinUncut.Encoding.QuestionEncoding
namespace OAI
sectionnamespace MinUncut.Preprocessopen MinUncutGames.Foundations.Hastad.SourceOccurrencesopen scoped BigOperatorsvariable {P X : Type} [Primcodable P] [Primcodable X] [AddCommMonoid X]
lemma c_rangeSum {f : P → ℕ → X} (hf : Computable₂ f) (hadd : Computable₂ (fun x y : X=>x+y)) : Computable₂ (fun p n=>((List.range n).map (f p)).sum) := by have hh := Computable.nat_rec (α:=P × ℕ) (σ:=X) Computable.snd (Computable.const 0) (hadd.comp (Computable.snd.comp Computable.snd) (hf.comp (Computable.fst.comp Computable.fst) (Computable.fst.comp Computable.snd))).to₂ exact hh.of_eq (by intro p induction p.2 with | zero => rfl | succ n ih => simp only [List.range_succ,List.map_append,List.map_singleton,List.sum_append, List.sum_singleton,ih])
namespace UEncodingvariable {A B Γ : P → Type}omit [AddCommMonoid X] inlemma Out.toFixed {a : UEncoding P A} {b : Encoding X} [Finite X] {f : ∀p,A p → X} (hf : a.Out f) : a.Map (fixed b) f := by obtain ⟨f',hr,he⟩:=hf exact ⟨_,(Primrec.dom_finite (fun x=>(b.code x).val)).to_comp.comp hr, by intro p x; dsimp only; rw [he]; rfl⟩
lemma out_sum {g : UEncoding P Γ} {a : UEncoding P A} [∀p,Fintype (A p)] {f : ∀p,Γ p × A p → X} (hf : (g.prod a).Out f) (hadd : Computable₂ (fun x y : X=>x+y)) : g.Out (fun p s=>∑x,f p (s,x)) := by obtain ⟨f',hf',hf⟩:=hf let raw : (P × ℕ) → ℕ → X := fun q i=>f' (q.1,q.2*(a.enc q.1).size+i) have hr : Computable₂ raw := by unfold raw exact hf'.comp ((Computable.fst.comp Computable.fst).pair (ca_add (ca_mul (Computable.snd.comp Computable.fst) (a.computableSize.comp (Computable.fst.comp Computable.fst))) Computable.snd)) refine ⟨fun q=>((List.range (a.enc q.1).size).map (raw q)).sum, (c_rangeSum hr hadd).comp Computable.id (a.computableSize.comp Computable.fst),?_⟩ intro p s dsimp only have he : ((a.enc p).enumerate.map (fun x=>f p (s,x))).sum=∑x,f p (s,x) := by classical have ht : (a.enc p).enumerate.toFinset=Finset.univ := by ext x; simp [(a.enc p).mem_enumerate x] rw [← List.sum_toFinset _ (a.enc p).nodup_enumerate,ht] rw [←he,Encoding.enumerate,List.ofFn_eq_map,List.map_map] rw [←finRange_values ((a.enc p).size),List.map_map] apply congrArg List.sum apply List.map_congr_left intro i hi have hh:=hf p (s,(a.enc p).code.symm i) change f' (p,(((g.enc p).prod (a.enc p)).code (s,(a.enc p).code.symm i)).val)=_ at hh rw [prod_code,Equiv.apply_symm_apply] at hh exact hh
instance primcodableF₂ : Primcodable MinUncut.Inner.F₂ := Primcodable.ofEquiv (Fin 2) MinUncut.Outer.fieldEncoding.code
abbrev field (P : Type) [Primcodable P] := fixed (P:=P) MinUncut.Outer.fieldEncoding
lemma out_field (a : UEncoding P A) {f : ∀p,A p → MinUncut.Inner.F₂} (hf : a.Map (field P) f) : a.Out f := hf.out 0lemma map_field_add {a : UEncoding P A} {f g : ∀p,A p → MinUncut.Inner.F₂} (hf : a.Map (field P) f) (hg : a.Map (field P) g) : a.Map (field P) (fun p x=>f p x+g p x) := ((out_field a hf).map₂ (out_field a hg) (Primrec.dom_finite _).to_comp).toFixedlemma map_field_mul {a : UEncoding P A} {f g : ∀p,A p → MinUncut.Inner.F₂} (hf : a.Map (field P) f) (hg : a.Map (field P) g) : a.Map (field P) (fun p x=>f p x*g p x) := ((out_field a hf).map₂ (out_field a hg) (Primrec.dom_finite _).to_comp).toFixedlemma map_field_sum {g : UEncoding P Γ} {a : UEncoding P A} [∀p,Fintype (A p)] {f : ∀p,Γ p × A p → MinUncut.Inner.F₂} (hf : (g.prod a).Map (field P) f) : g.Map (field P) (fun p s=>∑x,f p (s,x)) := (out_sum (out_field _ hf) (Primrec.dom_finite _).to_comp).toFixedend UEncodingend MinUncut.Preprocess
end
end OAI12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import Mathlibimport OAI.Computability.MinUncut.Encoding.UniformEncoding
namespace OAI
sectionnamespace MinUncut.Preprocessopen MinUncutGames.Foundations.Hastad.SourceOccurrencesnamespace UEncodingvariable {P : Type} [Primcodable P] {A B C Γ : P → Type}
def fixed {X : Type} (e : Encoding X) : UEncoding P (fun _=>X) := ⟨fun _=>e,Computable.const e.size⟩def bool : UEncoding P (fun _=>Bool) := fixed Encoding.booldef fin (n : P → ℕ) (hn : Computable n) : UEncoding P (fun p=>Fin (n p)) := ⟨fun p=>Encoding.fin (n p),hn⟩
lemma map_const {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,B p} (hf : Computable (fun p=>((b.enc p).code (f p)).val)) : a.Map b (fun p _=>f p) := ⟨_,hf.comp Computable.fst,by intros; rfl⟩
lemma bool_code (x : Bool) : (Encoding.bool.code x).val=x.toNat := by cases x <;> rfl
lemma map_bool_eq {a : UEncoding P A} {b : UEncoding P B} {f g : ∀p,A p → B p} [∀p,DecidableEq (B p)] (hf : a.Map b f) (hg : a.Map b g) : a.Map bool (fun p x=>decide (f p x=g p x)) := by obtain ⟨f',hf',hf⟩:=hf obtain ⟨g',hg',hg⟩:=hg refine ⟨fun q=>(decide (f' q=g' q)).toNat,?_,?_⟩ · exact (Primrec.dom_bool Bool.toNat).to_comp.comp (Primrec.eq.decide.to_comp.comp hf' hg') · intro p x dsimp only rw [hf,hg] change _=(Encoding.bool.code _).val rw [bool_code] congr 2 exact propext (Fin.val_inj.trans (b.enc p).code.injective.eq_iff)
lemma map_cond {a : UEncoding P A} {b : UEncoding P B} {c : ∀p,A p → Bool} {f g : ∀p,A p → B p} (hc : a.Map bool c) (hf : a.Map b f) (hg : a.Map b g) : a.Map b (fun p x=>if c p x then f p x else g p x) := by obtain ⟨c',hc',hc⟩:=hc obtain ⟨f',hf',hf⟩:=hf obtain ⟨g',hg',hg⟩:=hg refine ⟨fun q=>if c' q=1 then f' q else g' q,?_,?_⟩ · exact (Computable.cond (Primrec.eq.decide.to_comp.comp hc' (Computable.const 1)) hf' hg').of_eq (by intro q; simp) · intro p x dsimp only rw [hc,hf,hg] change (if (Encoding.bool.code (c p x)).val=1 then _ else _)=_ rw [bool_code] cases h:c p x <;> simp
lemma map_fixed {X Y : Type} (a : Encoding X) (b : Encoding Y) (f : X → Y) : (fixed (P:=P) a).Map (fixed b) (fun _ x=>f x) := by let table := List.ofFn (fun i : Fin a.size=>(b.code (f (a.code.symm i))).val) refine ⟨fun q=>(table[q.2]?).getD 0,?_,?_⟩ · exact Primrec.option_getD_default.to_comp.comp ((Primrec.list_getElem?₁ table).to_comp.comp Computable.snd) · intro p x dsimp only change (table[(a.code x).val]?).getD 0=(b.code (f x)).val simp [table,(a.code x).isLt]
lemma map_fixed_apply {X Y : Type} {a : UEncoding P A} (b : Encoding X) (c : Encoding Y) (op : X → Y) {f : ∀p,A p → X} (hf : a.Map (fixed b) f) : a.Map (fixed c) (fun p x=>op (f p x)) := map_comp hf (map_fixed b c op)
lemma map_binary {X Y Z : Type} {a : UEncoding P A} (b : Encoding X) (c : Encoding Y) (d : Encoding Z) (op : X → Y → Z) {f : ∀p,A p → X} {g : ∀p,A p → Y} (hf : a.Map (fixed b) f) (hg : a.Map (fixed c) g) : a.Map (fixed d) (fun p x=>op (f p x) (g p x)) := map_comp (map_pair hf hg) (map_fixed (b.prod c) d (fun x=>op x.1 x.2))
lemma map_not {a : UEncoding P A} {f : ∀p,A p → Bool} (hf : a.Map bool f) : a.Map bool (fun p x=>!(f p x)) := map_fixed_apply Encoding.bool Encoding.bool Bool.not hflemma map_and {a : UEncoding P A} {f g : ∀p,A p → Bool} (hf : a.Map bool f) (hg : a.Map bool g) : a.Map bool (fun p x=>f p x && g p x) := map_binary Encoding.bool Encoding.bool Encoding.bool Bool.and hf hglemma map_or {a : UEncoding P A} {f g : ∀p,A p → Bool} (hf : a.Map bool f) (hg : a.Map bool g) : a.Map bool (fun p x=>f p x || g p x) := map_binary Encoding.bool Encoding.bool Encoding.bool Bool.or hf hg
end UEncodingend MinUncut.Preprocess
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288import Mathlibimport OAI.Computability.MinUncut.Search.UniformFindimport OAI.Computability.MinUncut.Estimates.UniformAlgebraimport OAI.Computability.MinUncut.Analysis.UniformCube
namespace OAI
namespace MinUncut.Preprocess.Sourceopen MinUncutGames.Foundations MinUncutGames.Foundations.Targetopen PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrencesopen MinUncutGames.Reduction.CloneGapopen MinUncut.SourceTemplate UEncoding
abbrev Par := ℕ × ℕabbrev up {A : ℕ → Type} (a : UEncoding ℕ A) : UEncoding Par (fun p=>A p.1) := a.pullback Prod.fst Computable.fst
def ls : UEncoding Par (fun p=>I p.1) := up leftsdef rs : UEncoding Par (fun p=>J p.1) := up rightsdef fc := ls.function booldef gc := rs.function booldef keys : UEncoding Par (fun p=>LocalKey p.1) := fc.sum (gc.sum (fixed Encoding.unit))
variable {Γ : Par → Type} {e : UEncoding Par Γ}lemma map_rawLocal {v : ∀p,Γ p → J p.1 → Bool} {π : ∀p,Γ p → J p.1 → I p.1} {f : ∀p,Γ p → Cube (I p.1)} {g μ : ∀p,Γ p → Cube (J p.1)} (hv : e.Map gc v) (hπ : e.Map (rs.function ls) π) (hf : e.Map fc f) (hg : e.Map gc g) (hμ : e.Map gc μ) : e.Map keys.equation (fun p x=>rawLocal (v p x) (π p x) (f p x) (g p x) (μ p x)) := by have ha : e.Map ls (fun p _=>leftAnchor p.1) := map_lambda (map_false (e.prod (up positions))) have hfirst := map_comp (map_representative hf ha) (map_inl fc (gc.sum (fixed Encoding.unit))) have hdummy : e.Map keys (fun _ _=>Sum.inr (Sum.inr ())) := map_comp (map_comp (map_const (Computable.const 0)) (map_inr gc (fixed Encoding.unit))) (map_inr fc (gc.sum (fixed Encoding.unit))) have hnone : e.Map keys.equation (fun p x=> ⟨.inl (representative (leftAnchor p.1) (f p x)),.inr (.inr ()),.inr (.inr ()),f p x (leftAnchor p.1)⟩) := map_equation hfirst hdummy hdummy (map_apply hf ha) have hright (h : e.Map gc g) : (e.prod rs).Map keys (fun p x=>.inr (.inl (paddedRep (v p x.1) x.2 (g p x.1)))) := map_comp (map_comp (map_padded hv.first h.first (map_snd e rs)) (map_inl gc (fixed Encoding.unit))) (map_inr fc (gc.sum (fixed Encoding.unit))) have hthird := map_thirdQuery hπ hf hg hμ have hsome : (e.prod rs).Map keys.equation (fun p x=> ⟨.inl (representative (leftAnchor p.1) (f p x.1)), .inr (.inl (paddedRep (v p x.1) x.2 (g p x.1))), .inr (.inl (paddedRep (v p x.1) x.2 (thirdQuery (π p x.1) (f p x.1) (g p x.1) (μ p x.1)))), f p x.1 (leftAnchor p.1) ^^ f p x.1 (π p x.1 x.2) ^^ μ p x.1 x.2⟩) := by exact map_equation hfirst.first (hright hg) (map_comp (map_comp (map_padded hv.first hthird.first (map_snd e rs)) (map_inl gc (fixed Encoding.unit))) (map_inr fc (gc.sum (fixed Encoding.unit)))) (map_xor (map_xor (map_apply hf ha).first (map_apply hf.first (map_apply hπ.first (map_snd e rs)))) (map_apply hμ.first (map_snd e rs))) apply (map_comp (map_pair (map_id e) (map_find_apply hv)) (map_option_elim hnone hsome)).ofEq intro p x rfl
def ds : UEncoding Par (fun p=>Fin p.2) := fin Prod.snd Computable.snddef tapes : UEncoding Par (fun p=>SourceTape.TestTape (I p.1) (J p.1) p.2) := fc.prod ((rs.function ds).prod gc)def sigs := up signaturesdef sls := up slotContextsdef context := (sigs.prod sls).prod tapes
lemma map_context_signature : context.Map sigs (fun _ x=>x.1.1) := (map_fst sigs sls).firstlemma map_context_slot : context.Map sls (fun _ x=>x.1.2) := (map_snd sigs sls).firstlemma map_context_first : context.Map fc (fun _ x=>x.2.1) := map_comp (map_snd _ _) (map_fst _ _)lemma map_context_last : context.Map gc (fun _ x=>x.2.2.2) := ((map_snd (rs.function ds) gc).second (c:=fc)).second (c:=sigs.prod sls)lemma map_context_noiseTape : context.Map (rs.function ds) (fun _ x=>x.2.2.1) := ((map_fst (rs.function ds) gc).second (c:=fc)).second (c:=sigs.prod sls)lemma map_context_valid : context.Map gc (fun _ x=>x.1.1.valid) := map_lambda (map_comp (map_pair map_context_signature.first (map_snd context rs)) (map_valid.pullback Computable.fst))lemma map_context_project : context.Map (rs.function ls) (fun _ x=>x.1.1.project x.1.2) := by have hh := (map_project (g:=((signatures.prod slotContexts).prod rights)) (map_fst signatures slotContexts).first (map_snd signatures slotContexts).first (map_snd _ _)).pullback (f:=(Prod.fst : Par → ℕ)) Computable.fst exact map_lambda (map_comp (map_pair (map_pair map_context_signature.first map_context_slot.first) (map_snd context rs)) hh)lemma map_context_noise : context.Map gc (fun _ x=>MinUncutGames.Reduction.FiniteNoise.realizedNoise x.2.2.1) := map_lambda (map_value_zero (map_apply map_context_noiseTape.first (map_snd context rs)))lemma map_localEquation : context.Map keys.equation (fun _ x=>x.1.1.equation x.1.2 x.2) := by apply (map_rawLocal map_context_valid map_context_project map_context_first map_context_last map_context_noise).ofEq intro p x exact rawLocal_eq x.1.1.valid (x.1.1.project x.1.2) x.2end MinUncut.Preprocess.Source
noncomputable sectionnamespace MinUncut.Preprocess.Syntaxopen MinUncutGames.Foundations.PCPopen MinUncutGames.Foundations.Hastad.SourceOccurrencesopen MinUncutGames.Foundations.Hastad.SourceContextsopen MinUncut.Costed MinUncut.SourceTemplate UEncodingvariable {P Q : Type} [Primcodable P] [Primcodable Q] {A : P → Type} {c : UEncoding P A}lemma C.precomp {a : Q → AExpr} (ha : C a) {f : P → Q} (hf : Computable f) : C (fun p=>a (f p)) := Computable.comp ha hflemma O.tupleDigit {i : ∀p,A p → ℕ} (hi : c.Out i) : O c (fun p x=>tupleDigit (i p x)) := ((O.fixed (.reg 0)).div ((O.fixed (.reg 2)).pow hi)).mod (O.fixed (.reg 2))lemma O.slotWord {i j : ∀p,A p → ℕ} {s : ∀p,A p → Slot} (hi : c.Out i) (hs : c.Map (UEncoding.fixed slotEncoding) s) (hj : c.Out j) : O c (fun p x=>slotWord (i p x) (s p x) (j p x)) := by have hn := (out_code (UEncoding.fixed (P:=P) slotEncoding)).comp hs have hc := (out_const c (Computable.const 2)).map₂ hn (ca_mul Computable.fst Computable.snd) have hb := hc.map₂ hj (ca_add Computable.fst Computable.snd) exact ((O.fixed (.const 3)).add ((O.fixed (.const 6)).mul (O.tupleDigit hi))).add (.const hb) |>.at
abbrev unitN : UEncoding ℕ (fun _=>Unit) := UEncoding.fixed Encoding.unitlemma c_positiveExpr : C positiveExpr := by have hi : ((unitN.prod Source.positions).prod Source.slots).Out (fun _ x=>x.1.2.val) := (out_code Source.positions).second.first have hs := map_snd (unitN.prod Source.positions) Source.slots have hw := O.slotWord hi hs (out_const _ (Computable.const 1)) exact (hw.functionExpr (Computable.const 2) |>.functionExpr (Computable.const (2^3))).toClemma c_sameExpr : C sameExpr := by let c := (unitN.prod Source.coordinates).prod Source.coordinates have ha : c.Map Source.coordinates (fun _ x=>x.1.2) := (map_snd unitN Source.coordinates).first have hb : c.Map Source.coordinates (fun _ x=>x.2) := map_snd _ _ have hai := (out_code Source.positions).comp (map_comp ha (map_fst _ _)) have hbi := (out_code Source.positions).comp (map_comp hb (map_fst _ _)) have has := map_comp ha (map_snd _ _) have hbs := map_comp hb (map_snd _ _) have hzero := out_const c (Computable.const 0) have hw := (O.slotWord hai has hzero).eq (O.slotWord hbi hbs hzero) exact (hw.functionExpr (Computable.const 2) |>.functionExpr (ca_pow (Computable.const 2) (ca_mul Computable.id (Computable.const 3)))).toClemma c_signatureExpr : C signatureExpr := by have hconst := C.const (ca_pow (ca_pow (Computable.const 2) (ca_mul Computable.id (Computable.const 3))) (ca_mul Computable.id (Computable.const 3))) exact c_sameExpr.add (hconst.mul c_positiveExpr)lemma O.sourceLookup {u : P → ℕ} (hu : Computable u) {f : ∀p,A p × Signature (u p) → ℕ} (hf : (c.prod (Source.signatures.pullback u hu)).Out f) : O c (fun p x=>signatureLookup (fun s=>f p (x,s))) := (O.fromC (c_signatureExpr.precomp hu)).lookup (out_constantTable hf)lemma map_sourceSlot {u : P → ℕ} (hu : Computable u) {s : ∀p,A p → SlotContext (u p)} (hs : c.Map (Source.slotContexts.pullback u hu) s) : (c.prod (fin u hu)).Map (fixed slotEncoding) (fun p x=>s p x.1 x.2) := by have ht : c.Map ((fin u hu).function (fixed slotEncoding)) s := hs exact map_apply ht.first (map_snd c (fin u hu))lemma O.sourceSampled {u : P → ℕ} (hu : Computable u) {s : ∀p,A p → SlotContext (u p)} (hs : c.Map (Source.slotContexts.pullback u hu) s) : O c (fun p x=>sampledExpr (s p x)) := by let d := c.prod (fin u hu) have hi : d.Out (fun _ x=>x.2.val) := (out_code (fin u hu)).second have hx := map_sourceSlot hu hs have hw : O d (fun p x=>MinUncut.SourceTemplate.slotWord x.2.val (s p x.1 x.2) 0) := O.slotWord hi hx (out_const d (Computable.const 0)) have hp : O d (fun _ x=>(AExpr.reg 1).pow x.2.val) := (O.fixed (.reg 1)).pow hi 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 exact hh.sum_fin huend MinUncut.Preprocess.Syntax
namespace MinUncut.Preprocess.Faceopen MinUncut.Inner MinUncut.FiniteProofopen MinUncutGames.Foundations.Hastad.SourceOccurrencesopen UEncodingopen scoped BigOperatorsvariable {P : Type} [Primcodable P]variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)def axes := fin m hmdef values := fin n hndef points := (axes m hm).function (values n hn)def rowPairs := (axes m hm).prod (points m n hm hn)def rowGood (p : P) (x : Fin (m p) × Point (m p) (n p)) : Bool := decide (x.2 x.1=⟨0,hnpos p⟩)lemma map_rowGood : (rowPairs m n hm hn).Map bool (rowGood m n hnpos) := by exact map_bool_eq (map_apply (map_snd (axes m hm) (points m n hm hn)) (map_fst _ _)) (map_const (Computable.const 0))
def rowEquiv (p : P) : Row (m p) (n p) ≃ {x:Fin (m p) × Point (m p) (n p) // rowGood m n hnpos p x=true} where toFun r := ⟨(r.1,fun j=>if h:j=r.1 then ⟨0,hnpos p⟩ else r.2 ⟨j,h⟩),by simp [rowGood]⟩ invFun r := ⟨r.val.1,fun j=>r.val.2 j.val⟩ left_inv r := by dsimp only refine Sigma.ext (by rfl) ?_ apply heq_of_eq funext j exact dite_eq_right j.property right_inv r := by apply Subtype.ext dsimp only refine Prod.ext (by rfl) ?_ funext j by_cases h:j=r.val.1 · subst j dsimp only split · exact ((of_decide_eq_true r.property) : r.val.2 r.val.1=⟨0,hnpos p⟩).symm · rename_i hh; exact False.elim (hh rfl) · exact dite_eq_right h
def rows : UEncoding P (fun p=>Row (m p) (n p)) := ((rowPairs m n hm hn).restrict (rowGood m n hnpos) (map_rowGood m n hm hn hnpos)).ofEquiv (rowEquiv m n hnpos)
lemma map_faceRow : ((points m n hm hn).prod (axes m hm)).Map (rows m n hm hn hnpos) (fun _ x=>⟨x.2,face x.1 x.2⟩) := by let pt:=points m n hm hn let ax:=axes m hm let rs:=rowPairs m n hm hn let c:=pt.prod ax have hi : c.Map ax (fun _ x=>x.2) := map_snd _ _ have hx : c.Map pt (fun _ x=>x.1) := map_fst _ _ have hy : (c.prod ax).Map ax (fun _ x=>x.2) := map_snd _ _ have hz : (c.prod ax).Map (values n hn) (fun p _=>⟨0,hnpos p⟩) := map_const (Computable.const 0) have hw : (c.prod ax).Map (values n hn) (fun p x=>if x.2=x.1.2 then ⟨0,hnpos p⟩ else x.1.1 x.2) := by apply (map_cond (map_bool_eq hy hi.first) hz (map_apply hx.first hy)).ofEq intro p x simp only [decide_eq_true_eq] have hp := map_pair hi (map_lambda hw) 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 intro p x simp [rowGood] have hmk:=map_restrict_mk (map_rowGood m n hm hn hnpos) hp hg apply (map_comp hmk (map_from _ (rowEquiv m n hnpos))).ofEq intro p x refine Sigma.ext (by rfl) ?_ apply heq_of_eq funext j exact ite_eq_right j.property
lemma map_faceSum : ((rows m n hm hn hnpos).function (field P)).Map ((points m n hm hn).function (field P)) (fun p x=>faceSum (m p) (n p) x) := by let r:=rows m n hm hn hnpos let v:=points m n hm hn let ax:=axes m hm let c:=(r.function (field P)).prod v have hx : (c.prod ax).Map v (fun _ x=>x.1.2) := (map_snd _ _).first have hi : (c.prod ax).Map ax (fun _ x=>x.2) := map_snd _ _ have hr : (c.prod ax).Map r (fun _ x=>⟨x.2,face x.1.2 x.2⟩) := map_comp (map_pair hx hi) (map_faceRow m n hm hn hnpos) have hf : (c.prod ax).Map (r.function (field P)) (fun _ x=>x.1.1) := (map_fst _ _).first exact map_lambda (map_field_sum (map_apply hf hr))
def codeGood (p : P) (x : Point (m p) (n p) → F₂) : Bool := decide (∃f:Row (m p) (n p) → F₂,faceSum (m p) (n p) f=x)include hnpos inlemma map_codeGood : ((points m n hm hn).function (field P)).Map bool (codeGood m n) := by let r:=(rows m n hm hn hnpos).function (field P) let v:=(points m n hm hn).function (field P) have hh:=map_exists (map_bool_eq ((map_faceSum m n hm hn hnpos).second (c:=v)) (map_fst v r)) apply hh.ofEq intro p x simp only [codeGood,decide_eq_true_eq]
def codeEquiv (p : P) : Code (m p) (n p) ≃ {x:Point (m p) (n p) → F₂ // codeGood m n p x=true} where toFun x := ⟨x.val,by simpa only [codeGood,decide_eq_true_eq] using (LinearMap.mem_range.mp x.property)⟩ invFun x := ⟨x.val,LinearMap.mem_range.mpr (by simpa only [codeGood,decide_eq_true_eq] using x.property)⟩ left_inv _ := rfl right_inv _ := rfl
def codes : UEncoding P (fun p=>Code (m p) (n p)) := (((points m n hm hn).function (field P)).restrict (codeGood m n) (map_codeGood m n hm hn hnpos)).ofEquiv (codeEquiv m n)lemma map_codeVal : (codes m n hm hn hnpos).Map ((points m n hm hn).function (field P)) (fun _ x=>x.val) := by have hh := map_comp (map_to (((points m n hm hn).function (field P)).restrict (codeGood m n) (map_codeGood m n hm hn hnpos)) (codeEquiv m n)) (map_restrict_val ((points m n hm hn).function (field P)) (codeGood m n) (map_codeGood m n hm hn hnpos)) exact hh.ofEq (by intros; rfl)lemma map_codeMk {Γ : P → Type} {g : UEncoding P Γ} {f : ∀p,Γ p → Point (m p) (n p) → F₂} (hf : g.Map ((points m n hm hn).function (field P)) f) (h : ∀p x,∃a:Row (m p) (n p) → F₂,faceSum (m p) (n p) a=f p x) : g.Map (codes m n hm hn hnpos) (fun p x=>⟨f p x,LinearMap.mem_range.mpr (h p x)⟩) := by have hh:=map_restrict_mk (map_codeGood m n hm hn hnpos) hf (by intro p x; simp only [codeGood,decide_eq_true_eq]; exact h p x) exact map_comp hh (map_from _ (codeEquiv m n))
end MinUncut.Preprocess.Face
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298import Mathlibimport OAI.Computability.MinUncut.Estimates.UniformOutputimport OAI.Computability.MinUncut.Graphs.CanonicalSamplerGraphimport OAI.Computability.MinUncut.Estimates.BlocksEffectivity
namespace OAI
sectionnamespace MinUncut.Preprocess.UEncodingopen MinUncutGames.Foundations.Hastad.SourceOccurrences MinUncutGames.Reduction.CloneGapvariable {P : Type} [Primcodable P] {A B : P → Type} {X : Type} [Primcodable X]lemma out_elimSum {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,A p → X} {g : ∀p,B p → X} (hf : a.Out f) (hg : b.Out g) : (a.sum b).Out (fun p x=>Sum.elim (f p) (g p) x) := by obtain ⟨f',hfr,hf⟩:=hf obtain ⟨g',hgr,hg⟩:=hg let sz : P × ℕ → ℕ := fun p=>(a.enc p.1).size have hs : Computable sz := a.computableSize.comp Computable.fst let raw : P × ℕ → X := fun x=>if x.2<sz x then f' x else g' (x.1,x.2-sz x) refine ⟨raw,?_,?_⟩ · exact (Computable.cond (ca_natLt Computable.snd hs).decide hfr (hgr.comp (Computable.fst.pair (ca_sub Computable.snd hs)))).of_eq (by intro p; simp only [raw,Bool.cond_eq_ite,decide_eq_true_eq]) · intro p x cases x with | inl x => change (if ((a.enc p).code x).val<(a.enc p).size then _ else _)=_ rw [ite_eq_left ((a.enc p).code x).isLt] change f' (p,((a.enc p).code x).val)=f p x exact hf p x | inr x => change (if (a.enc p).size+((b.enc p).code x).val<(a.enc p).size then _ else _)=_ rw [ite_eq_right (by omega)] change g' (p,(a.enc p).size+((b.enc p).code x).val-(a.enc p).size)=_ rw [Nat.add_sub_cancel_left,hg] rfllemma map_eqTuple (a : UEncoding P A) : a.equation.Map (a.prod (a.prod (a.prod bool))) (fun p e=>equationEquiv (A p) e) := map_to _ (fun p=>equationEquiv (A p))lemma map_eqFirst (a : UEncoding P A) : a.equation.Map a (fun _ e=>e.first) := by have hh := map_comp (map_eqTuple a) (map_fst a (a.prod (a.prod bool))) exact hhlemma map_eqSecond (a : UEncoding P A) : a.equation.Map a (fun _ e=>e.second) := by have hh := map_comp (map_eqTuple a) (map_snd a (a.prod (a.prod bool))) have hh := map_comp hh (map_fst a (a.prod bool)) exact hhlemma map_eqThird (a : UEncoding P A) : a.equation.Map a (fun _ e=>e.third) := by have hh := map_comp (map_eqTuple a) (map_snd a (a.prod (a.prod bool))) have hh := map_comp hh (map_snd a (a.prod bool)) have hh := map_comp hh (map_fst a bool) exact hhlemma map_eqRhs (a : UEncoding P A) : a.equation.Map bool (fun _ e=>e.rhs) := by have hh := map_comp (map_eqTuple a) (map_snd a (a.prod (a.prod bool))) have hh := map_comp hh (map_snd a (a.prod bool)) have hh := map_comp hh (map_snd a bool) exact hhend MinUncut.Preprocess.UEncodingnamespace MinUncut.Preprocess.Sourceopen MinUncutGames.Foundations.Hastad.SourceOccurrences MinUncut.SourceTemplate UEncodinglemma out_keyTag : keys.Out (fun _ x=>keyTag x) := by apply (out_elimSum (out_const fc (Computable.const 0)) (out_elimSum (out_const gc (Computable.const 1)) (out_const (fixed Encoding.unit) (Computable.const 2)))).ofEq intro p x cases x with | inl _=> rfl | inr x=>cases x <;> rfllemma out_keyTable : keys.Out (fun _ x=>keyTable x) := by apply (out_elimSum (out_code fc) (out_elimSum (out_code gc) (out_const (fixed Encoding.unit) (Computable.const 0)))).ofEq intro p x cases x with | inl _=> rfl | inr x=>cases x <;> rflend MinUncut.Preprocess.Source
endnamespace MinUncut.SourceTemplateopen MinUncutGames.Foundations MinUncutGames.Foundations.Targetopen PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrencesopen MinUncutGames.Reduction MinUncut.Costednoncomputable section
def sourceExpressions (u D : ℕ) : List AExpr := (slotContextEncoding u).enumerate.flatMap (fun s=> (testTapeEncoding u D).enumerate.flatMap (equationExpressions s))
lemma sourceExpressions_eval (F : Formula) {u D : ℕ} (c : ClauseContext F u) : (sourceExpressions u D).map (fun e=>e.eval (inputTuple F c))= (slotContextEncoding u).enumerate.flatMap (fun s=> (testTapeEncoding u D).enumerate.flatMap (fun t=> SourceEncoding.equationWords (sourceEquation F u D ((c,s),t)))) := by simp only [sourceExpressions,List.map_flatMap,equationExpressions_eval]
lemma emitted_source (F : Formula) (u D : ℕ) : Blocks.emitted (sourceExpressions u D) (F.clauses.length^u) (Complexity.formulaWords F)= (rawSourceList F u D).flatMap SourceEncoding.equationWords := by rw [Blocks.emitted,←GraphRegisters.finRange_vals,Hastad.SourceEnumeration.rawSourceList_flatMap] have hc : (clauseEncoding F u).enumerate= (List.finRange (F.clauses.length^u)).map (clauseEncoding F u).code.symm := by exact List.ofFn_eq_map rw [hc] simp only [List.flatMap_map] conv_rhs => erw [List.flatMap_map] apply congrArg (List.flatMap · (List.finRange (F.clauses.length^u))) funext z have he := sourceExpressions_eval (D:=D) F ((clauseEncoding F u).code.symm z) simp only [Blocks.block,inputTuple, Hastad.SourceEnumeration.testTapeEncoding_enumerate,List.flatMap_assoc,List.flatMap_map, sourceEquation] at he ⊢ erw [Equiv.apply_symm_apply] at he exact he
def sourceVariableExpr (u : ℕ) : AExpr := .add (.mul ((AExpr.reg 0).pow u) (.const (2^(2^u)))) (.add (.mul ((AExpr.reg 1).pow u) (.const (2^(8^u)))) (.const 1))def sourceCountExpr (u D : ℕ) : AExpr := .div (.mul ((AExpr.reg 1).pow u) (.const (sourceExpressions u D).length)) (.const 4)def sourceStageWords (u D : ℕ) (v : List ℕ) : List ℕ := (sourceVariableExpr u).eval v::(sourceCountExpr u D).eval v:: (Blocks.emitted (sourceExpressions u D) (((AExpr.reg 1).pow u).eval v) v++ Blocks.retained (sourceExpressions u D) (((AExpr.reg 1).pow u).eval v) v)def sourceStageProgram (u D : ℕ) : PolyProgram (sourceStageWords u D) := ((sourceVariableExpr u).program.cons ((sourceCountExpr u D).program.cons (Blocks.forward (sourceExpressions u D) ((AExpr.reg 1).pow u)))).ofEq (by intro v; rfl)
lemma sourceVariableExpr_eval (F : Formula) (u : ℕ) : (sourceVariableExpr u).eval (Complexity.formulaWords F)=nBits F u := by simp only [sourceVariableExpr,AExpr.eval,AExpr.eval_pow,Complexity.formulaWords,List.cons_append,List.nil_append, List.drop_zero,List.headI_cons,List.drop_succ_cons,nBits_eq]
lemma sourceCountExpr_eval (F : Formula) (u D : ℕ) : (sourceCountExpr u D).eval (Complexity.formulaWords F)=(rawSourceList F u D).length := by have h := congrArg List.length (emitted_source F u D) rw [Blocks.length_emitted] at h have hl : ((rawSourceList F u D).flatMap SourceEncoding.equationWords).length= (rawSourceList F u D).length*4 := by simp only [List.length_flatMap,SourceEncoding.equationWords,List.length_cons,List.length_nil] simp only [List.map_const',List.sum_replicate,nsmul_eq_mul,Nat.cast_id] rw [hl] at h simp only [sourceCountExpr,AExpr.eval,AExpr.eval_pow,Complexity.formulaWords,List.cons_append,List.nil_append, List.drop_zero,List.headI_cons,List.drop_succ_cons,h] omega
lemma sourceStageWords_spec (F : Formula) (u D : ℕ) (hD : 0<D) (hne : F.clauses≠[]) : ∃junk, sourceStageWords u D (Complexity.formulaWords F)= SourceEncoding.inputWords (sourceInput F u D hD)++junk := by refine ⟨Blocks.retained (sourceExpressions u D) (F.clauses.length^u) (Complexity.formulaWords F),?_⟩ unfold sourceStageWords rw [sourceVariableExpr_eval,sourceCountExpr_eval] have ht : ((AExpr.reg 1).pow u).eval (Complexity.formulaWords F)=F.clauses.length^u := by simp only [AExpr.eval_pow,AExpr.eval,Complexity.formulaWords,List.cons_append,List.nil_append, List.drop_succ_cons,List.drop_zero,List.headI_cons] rw [ht,emitted_source] simp only [SourceEncoding.inputWords,sourceInput,sourceList_nonempty F u D hne, List.cons_append,List.nil_append]endend MinUncut.SourceTemplate
noncomputable sectionnamespace MinUncut.Preprocess.Syntaxopen MinUncutGames.Foundations.PCPopen MinUncutGames.Foundations.Hastad.SourceOccurrencesopen MinUncutGames.Foundations.Hastad.SourceContextsopen MinUncut.Costed MinUncut.SourceTemplate UEncodingvariable {P : Type} [Primcodable P] {A : P → Type} {c : UEncoding P A}lemma O.sourceAddress {u : P → ℕ} (hu : Computable u) {s : ∀p,A p → SlotContext (u p)} (hs : c.Map (Source.slotContexts.pullback u hu) s) {f : ∀p,A p × Signature (u p) → LocalKey (u p)} (hf : (c.prod (Source.signatures.pullback u hu)).Map (Source.keys.pullback (fun p=>(u p,0)) (hu.pair (Computable.const 0))) f) : O c (fun p x=>addressExpr (s p x) (fun S=>f p (x,S))) := by have hp := hu.pair (Computable.const 0) have tag := O.sourceLookup hu ((Source.out_keyTag.pullback hp).comp hf) have tab := O.sourceLookup hu ((Source.out_keyTable.pullback hp).comp hf) have reg1 : O c (fun p _=>(AExpr.reg 1).pow (u p)) := (O.fixed (.reg 1)).pow (out_const c hu) have reg2 : O c (fun p _=>(AExpr.reg 2).pow (u p)) := (O.fixed (.reg 2)).pow (out_const c hu) have b2 := ca_pow (Computable.const 2) (ca_pow (Computable.const 2) hu) have b8 := ca_pow (Computable.const 2) (ca_pow (Computable.const 8) hu) have left := reg1.mul (O.const (out_const c b2)) have ha := left.add (reg2.mul (O.const (out_const c b8))) have hb := left.add (tab.add ((O.const (out_const c b8)).mul (O.fixed (.reg 0)))) have hc := tab.add ((O.const (out_const c b2)).mul (O.sourceSampled hu hs)) exact (tag.eq (O.fixed (.const 0))).cond ((tag.eq (O.fixed (.const 1))).cond ha hb) hc
abbrev sourceArgs := Source.sls.prod Source.tapeslemma map_sourceContext : (sourceArgs.prod Source.sigs).Map Source.context (fun _ x=>((x.2,x.1.1),x.1.2)) := map_pair (map_pair (map_snd _ _) ((map_fst _ _).first)) ((map_snd _ _).first)lemma out_sourceEquationExpressions : sourceArgs.Out (fun _ x=>(equationExpressions x.1 x.2).map (fun e=>e.program.code)) := by have hs := map_fst Source.sls Source.tapes have he := map_comp map_sourceContext Source.map_localEquation have h1 := map_comp he (map_eqFirst Source.keys) have h2 := map_comp he (map_eqSecond Source.keys) have h3 := map_comp he (map_eqThird Source.keys) have hb := (out_boolNat (map_comp he (map_eqRhs Source.keys))) have a := O.sourceAddress (c:=sourceArgs) Computable.fst hs h1 have b := O.sourceAddress (c:=sourceArgs) Computable.fst hs h2 have d := O.sourceAddress (c:=sourceArgs) Computable.fst hs h3 have e := O.sourceLookup (c:=sourceArgs) Computable.fst hb exact a.cons (b.cons (d.cons (e.cons (out_const sourceArgs (Computable.const [])))))lemma c_sourceExpressions : Computable (fun p : Source.Par=> (sourceExpressions p.1 p.2).map (fun e=>e.program.code)) := by have h := (out_list out_sourceEquationExpressions).enumerate apply (Primrec.list_flatten.to_comp.comp (Primrec.list_flatten.to_comp.comp h)).of_eq intro p simp only [sourceExpressions,List.flatMap_def,List.map_flatten,List.flatten_flatten,List.map_map,Function.comp_def] rfl
open MinUncut.Costed MinUncut.SourceTemplate MinUncut.CodeEffectivelemma c_sourceVariableExpr : C sourceVariableExpr := by exact ((C.fixed (.reg 0)).pow Computable.id |>.mul (C.const (ca_pow (Computable.const 2) (ca_pow (Computable.const 2) Computable.id)))).add (((C.fixed (.reg 1)).pow Computable.id |>.mul (C.const (ca_pow (Computable.const 2) (ca_pow (Computable.const 8) Computable.id)))).add (C.fixed (.const 1)))lemma c_sourceCountExpr : C (fun p : Source.Par=>sourceCountExpr p.1 p.2) := by have hl : Computable (fun p : Source.Par=>(sourceExpressions p.1 p.2).length) := (Computable.list_length.comp c_sourceExpressions).of_eq (fun p=>List.length_map ..) exact (((C.fixed (.reg 1)).pow Computable.fst).mul (C.const hl)).div (C.fixed (.const 4))lemma c_sourceStageCode : Computable (fun p : Source.Par=>(sourceStageProgram p.1 p.2).code) := by have hf := p_forwardCode.to_comp.comp c_sourceExpressions ((C.fixed (.reg 1)).pow Computable.fst) have hh := computable_cons.comp (c_sourceVariableExpr.precomp Computable.fst) (computable_cons.comp c_sourceCountExpr hf) apply hh.of_eq intro p rw [forwardCode_eq] rflend MinUncut.Preprocess.Syntax
open scoped BigOperatorsnamespace MinUncut.Costed.SourceWordsopen MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplateopen MinUncut.PathRealization MinUncut.FiniteProof MinUncutGames.Reduction MinUncut.SourceBridgeopen MinUncutGames.Foundations.Hastad.SourceOccurrencesattribute [local instance] Classical.propDecidable
variable {t k m n : ℕ} {g : MinUncut.FiniteGaussian.GridData}
lemma sum_flatMap_nat {A : Type*} (l : List A) (f : A → List ℕ) : (l.flatMap f).sum=(l.map (fun a=>(f a).sum)).sum := by induction l with | nil => rfl | cons a l ih => simp only [List.flatMap_cons,List.sum_append,List.map_cons,List.sum_cons,ih]
lemma tupleList_sum (input : SourceEncoding.Input) (f : (Fin t → Fin input.equations.length) → ℕ) : ((tupleList input t).map f).sum=∑u,f u := by simp only [tupleList,←List.ofFn_eq_map,List.map_ofFn,List.sum_ofFn] exact Equiv.sum_comp finFunctionFinEquiv.symm f
lemma tupleDemands_failure (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) (E : Enumeration (Index (Fin t) k m n g)) (a : ℚ) (b : MinUncut.Outer.Test → ℚ) (σ η : ℚ) (y : Fin (paddedVariableEncoding input.«variables» t).size → Bool) : listFailure (tupleDemands input u E a b σ η) y= ∑e : Index (Fin t) k m n g,repetitions a b e*failure (allDemand (equations input) g σ η (occurrence (equations input) (u,e))) (y ∘ variableCode) := by unfold tupleDemands listFailure simp only [List.map_flatMap,sum_flatMap_nat,List.map_replicate,List.sum_replicate, nsmul_eq_mul,Nat.cast_id,failure_map] exact E.sum_values _
lemma generatedDemands_failure (input : SourceEncoding.Input) (E : Enumeration (Index (Fin t) k m n g)) (a : ℚ) (b : MinUncut.Outer.Test → ℚ) (σ η : ℚ) (y : Fin (paddedVariableEncoding input.«variables» t).size → Bool) : listFailure (generatedDemands input E a b σ η) y= ∑u,∑e : Index (Fin t) k m n g,repetitions a b e*failure (allDemand (equations input) g σ η (occurrence (equations input) (u,e))) (y ∘ variableCode) := by unfold generatedDemands listFailure rw [List.map_flatMap,sum_flatMap_nat] change ((tupleList input t).map (fun u=>listFailure (tupleDemands input u E a b σ η) y)).sum=_ simp only [tupleDemands_failure] exact tupleList_sum input _
lemma generated_failure_eq {J : ℕ} (P : Parameters J) (input : SourceEncoding.Input) [Nonempty (Fin input.equations.length)] (E : Enumeration (Index (Fin P.o.t) P.o.k P.d.m P.d.n P.grid)) (y : Fin (paddedVariableEncoding input.«variables» P.o.t).size → Bool) : listFailure (generatedDemands input E (rationalRate J P.d) (rationalBudgets J P.d P.o) (rationalSigma J) (rationalEta J)) y= listFailure (P.canonicalDemands (equations input)) y := by rw [generatedDemands_failure,Parameters.canonicalDemands,listFailure_map,listFailure_demandList] have he := Equiv.sum_comp (occurrence (k:=P.o.k) (m:=P.d.m) (n:=P.d.n) (g:=P.grid) (equations input)) (fun e=>multiplicity (P.denominator (Fin input.equations.length)) (P.weight (equations input) e)*failure (P.demand (equations input) e) (y ∘ variableCode)) rw [Fintype.sum_prod_type] at he rw [←he] apply Finset.sum_congr rfl intro u _ apply Finset.sum_congr rfl intro e _ congr 1 exact (occurrence_multiplicity (equations input) (by simpa only [Fintype.card_fin] using P.k_le) P.grid_pos.1 P.grid_pos.2 (rationalRate_bounds P.hJ P.d P.hd).1 (rationalRate_bounds P.hJ P.d P.hd).2 _ (rationalBudgets_pos P.hJ P.d P.hd P.o P.ho) u e).symmend MinUncut.Costed.SourceWords
end
end OAI123456789101112131415161718192021222324252627282930313233343536import Mathlibimport OAI.Computability.MinUncut.Estimates.UniformEquationimport OAI.Computability.MinUncut.Machines.UniformAlphabet
namespace OAI
sectionnoncomputable sectionnamespace MinUncut.Preprocess.Alphabetopen MinUncut.Inner MinUncut.FiniteProof MinUncut.Outeropen UEncodingvariable {P : Type} [Primcodable P]variable (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool)variable (hc : Computable (fun p=>(((MinUncutGames.Foundations.Hastad.SourceOccurrences.Encoding.fin (t p)).function MinUncutGames.Foundations.Hastad.SourceOccurrences.Encoding.bool).code (h p)).val))variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)def arrays : UEncoding P (fun p=>FaceArray (LocalTemplate.Alphabet (h p)) (m p) (n p)) := (Face.rows m n hm hn hnpos).function (forms t ht h hc)lemma map_labelCode : ((arrays t ht h hc m n hm hn hnpos).prod (labels t ht h hc)).Map (Face.codes m n hm hn hnpos) (fun _ x=>labelCode x.1 x.2) := by let r:=Face.rows m n hm hn hnpos let a:=arrays t ht h hc m n hm hn hnpos let l:=labels t ht h hc let c:=a.prod l have hb : (c.prod r).Map a (fun _ x=>x.1.1) := (map_fst _ _).first have hx : (c.prod r).Map l (fun _ x=>x.1.2) := (map_snd _ _).first have he : c.Map (r.function (field P)) (fun _ x r=>(x.1 r) x.2) := map_lambda (map_comp (map_pair (map_apply hb (map_snd _ _)) hx) (map_forms_apply t ht h hc)) exact Face.map_codeMk m n hm hn hnpos (map_comp he (Face.map_faceSum m n hm hn hnpos)) (by intro p x; exact ⟨_,rfl⟩)end MinUncut.Preprocess.Alphabet
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483import Mathlibimport OAI.Computability.MinUncut.Search.ParameterFieldsimport OAI.Computability.MinUncut.Search.UniformRationalimport OAI.Computability.MinUncut.Games.QuestionExpressionsimport OAI.Computability.MinUncut.Estimates.UniformFaceArrayimport OAI.Computability.MinUncut.Machines.UniformDemandAlphabetimport OAI.Computability.MinUncut.Estimates.UniformProduct
namespace OAI
noncomputable sectionnamespace MinUncut.Preprocessopen MinUncut.FiniteGaussianopen scoped BigOperatorslemma c_coefficient : Computable coefficient := ca_ratDiv (ca_ratPow (ca_const (-1)) Computable.id) (ca_ratMul (ca_ratPow (ca_const 2) Computable.id) (ca_ratCast (ca_factorial Computable.id)))lemma c_primitive : Computable₂ primitive := by have hc : Computable₂ (fun (p : ℕ × ℚ) (j : ℕ)=>coefficient j*p.2^(2*j+1)/(2*j+1)) := by apply ca_ratDiv · exact ca_ratMul (c_coefficient.comp Computable.snd) (ca_ratPow (Computable.snd.comp Computable.fst) (ca_add (ca_mul (ca_const 2) Computable.snd) (ca_const 1))) · exact ca_ratAdd (ca_ratMul (ca_const 2) (ca_ratCast Computable.snd)) (ca_const 1) exact ((c_rangeSum hc computable_ratAdd).comp Computable.id (ca_add (ca_mul (ca_const 2) Computable.fst) (ca_const 1))).of_eq (by intro p dsimp only [primitive] rw [←List.sum_toFinset _ List.nodup_range,List.toFinset_range] rfl)lemma c_qIntegral : Computable (fun p : ℕ × ℚ × ℚ=>qIntegral p.1 p.2.1 p.2.2) := ca_ratSub (c_primitive.comp Computable.fst (Computable.snd.comp Computable.snd)) (c_primitive.comp Computable.fst (Computable.fst.comp Computable.snd))lemma c_endpoint : Computable (fun p : ℚ × ℕ × ℕ=>endpoint p.1 p.2.1 p.2.2) := by unfold endpoint exact ca_ratAdd (computable_ratNeg.comp Computable.fst) (ca_ratDiv (ca_ratMul (ca_ratMul (ca_const 2) Computable.fst) (ca_ratCast (Computable.snd.comp Computable.snd))) (ca_ratCast (Computable.fst.comp Computable.snd)))attribute [local irreducible] endpoint qIntegral primitivelemma ca_endpoint {X : Type} [Primcodable X] {t : X → ℚ} {l i : X → ℕ} (ht : Computable t) (hl : Computable l) (hi : Computable i) : Computable (fun x=>endpoint (t x) (l x) (i x)) := by have hh := @Computable.comp X (ℚ × ℕ × ℕ) ℚ _ _ _ _ _ c_endpoint (ht.pair (hl.pair hi)) exact hh.of_eq (by intro x; rfl)lemma ca_qIntegral {X : Type} [Primcodable X] {r : X → ℕ} {a b : X → ℚ} (hr : Computable r) (ha : Computable a) (hb : Computable b) : Computable (fun x=>qIntegral (r x) (a x) (b x)) := by have hh := @Computable.comp X (ℕ × ℚ × ℚ) ℚ _ _ _ _ _ c_qIntegral (hr.pair (ha.pair hb)) exact hh.of_eq (by intro x; rfl)lemma c_midpoint : Computable (fun p : ℚ × ℕ × ℕ=>midpoint p.1 p.2.1 p.2.2) := by unfold FiniteGaussian.midpoint exact ca_ratDiv (ca_ratAdd c_endpoint (ca_endpoint Computable.fst (Computable.fst.comp Computable.snd) (ca_add (Computable.snd.comp Computable.snd) (ca_const 1)))) (ca_const 2)lemma c_rawCellWeight : Computable (fun p : GridData × ℕ=> qIntegral p.1.r (endpoint p.1.T p.1.L p.2) (endpoint p.1.T p.1.L (p.2+1)) / qIntegral p.1.r (-p.1.T) p.1.T) := by have hr:=c_gridData_r.comp (Computable.fst (α:=GridData) (β:=ℕ)) have ht:=ca_ratCast (c_gridData_T.comp (Computable.fst (α:=GridData) (β:=ℕ))) have hl:=c_gridData_L.comp (Computable.fst (α:=GridData) (β:=ℕ)) have he : Computable (fun p : GridData × ℕ=>endpoint p.1.T p.1.L p.2) := ca_endpoint ht hl Computable.snd have he' : Computable (fun p : GridData × ℕ=>endpoint p.1.T p.1.L (p.2+1)) := ca_endpoint ht hl (ca_add Computable.snd (ca_const 1)) have ha : Computable (fun p : GridData × ℕ=>qIntegral p.1.r (endpoint p.1.T p.1.L p.2) (endpoint p.1.T p.1.L (p.2+1))) := ca_qIntegral hr he he' have hb : Computable (fun p : GridData × ℕ=>qIntegral p.1.r (-p.1.T) p.1.T) := ca_qIntegral hr (computable_ratNeg.comp ht) ht exact ca_ratDiv ha hb
namespace Gridopen UEncoding MinUncut.Innervariable {P : Type} [Primcodable P]variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)variable (g : P → GridData) (hg : Computable g)def coordinates : UEncoding P (fun p=>TestCoordinates (m p) (n p)) := (Face.points m n hm hn).sum ((Face.points m n hm hn).sum (Face.codes m n hm hn hnpos))def cells := fin (fun p=>(g p).L) (c_gridData_L.comp hg)def samples := (coordinates m n hm hn hnpos).function (cells g hg)lemma out_midpoint : (cells g hg).Out (fun p i=>midpoint (g p).T (g p).L i.val) := ((out_const _ (ca_ratCast (c_gridData_T.comp hg))).pair ((out_const _ (c_gridData_L.comp hg)).pair (out_code (cells g hg)))).map c_midpointlemma out_cellWeight : (cells g hg).Out (fun p i=>cellWeight (g p).r (g p).T (g p).L i) := ((out_const _ hg).pair (out_code (cells g hg))).map c_rawCellWeightlemma out_gridWeight : (samples m n hm hn hnpos g hg).Out (fun p q=>gridWeight (g p) q) := by let a:=samples m n hm hn hnpos g hg let i:=coordinates m n hm hn hnpos exact out_prod ((out_cellWeight g hg).comp (map_apply (map_fst a i) (map_snd a i))) computable_ratMulend Gridend MinUncut.Preprocess
namespace MinUncut.Preprocess.Gridopen MinUncut.Inner MinUncut.FiniteGaussian UEncodingvariable {P : Type} [Primcodable P]variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)variable (g : P → GridData) (hg : Computable g)def indices := bool.prod (Face.codes m n hm hn hnpos)variable {Γ : P → Type} {c : UEncoding P Γ}lemma out_coord {q : ∀p,Γ p → TestCoordinates (m p) (n p) → Fin (g p).L} {i : ∀p,Γ p → TestCoordinates (m p) (n p)} (hq : c.Map (samples m n hm hn hnpos g hg) q) (hi : c.Map (coordinates m n hm hn hnpos) i) : c.Out (fun p x=>midpoint (g p).T (g p).L (q p x (i p x))) := (out_midpoint g hg).comp (map_apply hq hi)lemma out_sign {z : ∀p,Γ p → Code (m p) (n p)} {i : ∀p,Γ p → Point (m p) (n p)} (hz : c.Map (Face.codes m n hm hn hnpos) z) (hi : c.Map (Face.points m n hm hn) i) : c.Out (fun p x=>qSign ((z p x).val (i p x))) := (out_field c (map_apply (map_comp hz (Face.map_codeVal m n hm hn hnpos)) hi)).map (Primrec.dom_finite qSign).to_complemma out_scoreSummand (σ : P → ℚ) (hσ : Computable σ) : (((samples m n hm hn hnpos g hg).prod (indices m n hm hn hnpos)).prod (Face.points m n hm hn)).Out (fun p x=>(midpoint (g p).T (g p).L (x.1.1 (.inl x.2))+ (if x.1.2.1 then σ p else 0)*midpoint (g p).T (g p).L (x.1.1 (.inr (.inl x.2))))* qSign (x.1.2.2.val x.2)) := by let s:=samples m n hm hn hnpos g hg let z:=indices m n hm hn hnpos let pt:=Face.points m n hm hn let c:=(s.prod z).prod pt have hq : c.Map s (fun _ x=>x.1.1) := (map_fst _ _).first have hz : c.Map z (fun _ x=>x.1.2) := (map_snd _ _).first have hi : c.Map pt (fun _ x=>x.2) := map_snd _ _ have hx := out_coord m n hm hn hnpos g hg hq (map_comp hi (map_inl pt (pt.sum (Face.codes m n hm hn hnpos)))) have hy := out_coord m n hm hn hnpos g hg hq (map_comp (map_comp hi (map_inl pt (Face.codes m n hm hn hnpos))) (map_inr pt (pt.sum (Face.codes m n hm hn hnpos)))) have hs : c.Out (fun p x=>if x.1.2.1 then σ p else 0) := Out.cond (map_comp hz (map_fst _ _)) (out_const _ hσ) (out_const _ (ca_const 0)) exact (hx.ratAdd (hs.ratMul hy)).ratMul (out_sign m n hm hn hnpos (map_comp hz (map_snd _ _)) hi)lemma map_scoreTable (σ η : P → ℚ) (hσ : Computable σ) (hη : Computable η) : ((samples m n hm hn hnpos g hg).prod (indices m n hm hn hnpos)).Map bool (fun p x=>rationalScoreTable (σ p) (η p) (fun i=>midpoint (g p).T (g p).L (x.1 i)) x.2) := by let s:=samples m n hm hn hnpos g hg let z:=indices m n hm hn hnpos let pt:=Face.points m n hm hn let co:=Face.codes m n hm hn hnpos let c:=s.prod z have hq : c.Map s (fun _ x=>x.1) := map_fst _ _ have hz : c.Map z (fun _ x=>x.2) := map_snd _ _ have hc : c.Map co (fun _ x=>x.2.2) := map_comp hz (map_snd _ _) have hy := out_coord m n hm hn hnpos g hg hq (map_comp (map_comp hc (map_inr pt co)) (map_inr pt (pt.sum co))) have he : c.Out (fun p x=>if x.2.1 then η p else 0) := Out.cond (map_comp hz (map_fst _ _)) (out_const _ hη) (out_const _ (ca_const 0)) exact (out_sum (out_scoreSummand m n hm hn hnpos g hg σ hσ) computable_ratAdd).algebraicNonneg (he.ratMul hy) (out_const _ (ca_pow hn hm))end MinUncut.Preprocess.Grid
namespace MinUncut.Preprocessopen MinUncut.Inner MinUncut.FiniteProof MinUncut.FiniteGaussian MinUncut.Outeropen MinUncutGames.Foundations.Hastad.SourceOccurrences UEncodingopen scoped BigOperatorsattribute [local irreducible] gridWeightnamespace UEncodingvariable {P X : Type} [Primcodable P] [Primcodable X] {A : P → Type}lemma Out.unit {f : P → X} (hf : (fixed (P:=P) Encoding.unit).Out (fun p _=>f p)) : Computable f := by obtain ⟨g,hg,hh⟩:=hf exact (hg.comp (Computable.id.pair (Computable.const 0))).of_eq (fun p=>hh p ())lemma computable_prod [CommMonoid X] (a : UEncoding P A) [∀p,Fintype (A p)] {f : ∀p,A p → X} (hf : a.Out f) (hmul : Computable₂ (fun x y : X=>x*y)) : Computable (fun p=>∏x,f p x) := (out_prod hf.second hmul).unitend UEncodingabbrev tests (P : Type) [Primcodable P] : UEncoding P (fun _=>Test) := fixed SampleEnumeration.tests.encodinginstance primcodableTest : Primcodable Test := Primcodable.ofEquiv (Fin SampleEnumeration.tests.encoding.size) SampleEnumeration.tests.encoding.codenamespace Weightsvariable {P : Type} [Primcodable P]variable (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool)variable (hc : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (h p)).val))variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)variable (g : P → GridData) (hg : Computable g)def localSamples := (Alphabet.arrays t ht h hc m n hm hn hnpos).prod ((Alphabet.arrays t ht h hc m n hm hn hnpos).prod ((Face.codes m n hm hn hnpos).prod (Grid.samples m n hm hn hnpos g hg)))lemma out_rationalRowDensity (a : P → ℚ) (ha : Computable a) : ((Alphabet.forms t ht h hc).prod (Alphabet.forms t ht h hc)).Out (fun p x=>RowNoise.rationalRowDensity (a p) x.1 x.2) := by classical let c:=(Alphabet.forms t ht h hc).prod (Alphabet.forms t ht h hc) have hc' : Computable (fun p=>Fintype.card (Forms (LocalTemplate.Alphabet (h p)))) := computableCard (Alphabet.forms t ht h hc) have hi : c.Out (fun p x=>if x.2=x.1 then (Fintype.card (Forms (LocalTemplate.Alphabet (h p))):ℚ) else 0) := by apply (Out.cond (map_bool_eq (map_snd _ _) (map_fst _ _)) (out_const c (ca_ratCast hc')) (out_const c (ca_const 0))).ofEq intro p x simp only [decide_eq_true_eq] exact ((out_const c (ca_const 1)).ratSub (out_const c ha)).ratMul hi |>.ratAdd (out_const c ha)lemma out_rationalDensity (a : P → ℚ) (ha : Computable a) : ((Alphabet.arrays t ht h hc m n hm hn hnpos).prod (Alphabet.arrays t ht h hc m n hm hn hnpos)).Out (fun p x=>RowNoise.rationalDensity (a p) x.1 x.2) := by let ar:=Alphabet.arrays t ht h hc m n hm hn hnpos let ro:=Face.rows m n hm hn hnpos have hb : ((ar.prod ar).prod ro).Map ar (fun _ x=>x.1.1) := (map_fst _ _).first have hc' : ((ar.prod ar).prod ro).Map ar (fun _ x=>x.1.2) := (map_snd _ _).first have hr : ((ar.prod ar).prod ro).Map ro (fun _ x=>x.2) := map_snd _ _ exact out_prod ((out_rationalRowDensity t ht h hc a ha).comp (map_pair (map_apply hb hr) (map_apply hc' hr))) computable_ratMullemma out_noiseWeight (a : P → ℚ) (ha : Computable a) : (((Alphabet.arrays t ht h hc m n hm hn hnpos).prod (Alphabet.arrays t ht h hc m n hm hn hnpos)).prod (tests P)).Out (fun p x=>noiseWeight (a p) x.1.1 x.1.2 x.2) := by let ar:=Alphabet.arrays t ht h hc m n hm hn hnpos let c:=(ar.prod ar).prod (tests P) have he : c.Map bool (fun _ x=>decide (x.2=Test.second)) := map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun j=>decide (j=Test.second)) (map_snd _ _) exact (Out.cond he (out_rationalDensity t ht h hc m n hm hn hnpos a ha).first (out_const c (ca_const 1))).ofEq (by intro p x cases x.2 <;> simp only [noiseWeight,reduceCtorEq,decide_true,decide_false,Bool.false_eq_true,ite_false,ite_true] unfold RowNoise.rationalDensity apply Finset.prod_congr rfl intro r _ unfold RowNoise.rationalRowDensity split_ifs <;> rfl)lemma out_localWeight (a b : P → ℚ) (ha : Computable a) (hb : Computable b) : ((localSamples t ht h hc m n hm hn hnpos g hg).prod (tests P)).Out (fun p x=>localWeight (g p) (a p) (b p) x.2 x.1) := by let s:=localSamples t ht h hc m n hm hn hnpos g hg let c:=s.prod (tests P) let ar:=Alphabet.arrays t ht h hc m n hm hn hnpos have har : Computable (fun p=>(Fintype.card (FaceArray (LocalTemplate.Alphabet (h p)) (m p) (n p)):ℚ)⁻¹) := computable_ratInv.comp (ca_ratCast (computableCard ar)) have hco : Computable (fun p=>(Fintype.card (Code (m p) (n p)):ℚ)⁻¹) := computable_ratInv.comp (ca_ratCast (computableCard (Face.codes m n hm hn hnpos))) have hs : c.Map s (fun _ x=>x.1) := map_fst _ _ have hB : c.Map ar (fun _ x=>x.1.1) := map_comp hs (map_fst _ _) have hC : c.Map ar (fun _ x=>x.1.2.1) := map_comp (map_comp hs (map_snd _ _)) (map_fst _ _) have hq : c.Map (Grid.samples m n hm hn hnpos g hg) (fun _ x=>x.1.2.2.2) := map_comp (map_comp (map_comp hs (map_snd _ _)) (map_snd _ _)) (map_snd _ _) exact ((((out_const c har).ratMul (out_const c har)).ratMul (out_const c hco)).ratMul ((Grid.out_gridWeight m n hm hn hnpos g hg).comp hq)).ratMul ((out_noiseWeight t ht h hc m n hm hn hnpos a ha).comp (map_pair (map_pair hB hC) (map_snd _ _))) |>.ratDiv (out_const c hb)end Weightsnamespace Denominatorvariable {P : Type} [Primcodable P]variable (t m n : P → ℕ) (ht : Computable t) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)variable (g : P → GridData) (hg : Computable g)include ht hm hn hnpos inlemma c_faceCardBound : Computable (fun p=>faceCardBound (t p) (m p) (n p)) := ca_pow (ca_pow (ca_const 2) (ca_pow (ca_const 2) (ca_mul (ca_const 3) ht))) (computableCard (Face.rows m n hm hn hnpos))include hm hn hnpos hg inlemma c_gridDenominator : Computable (fun p=>gridDenominator (m p) (n p) (g p)) := by let a : UEncoding P (fun p=>TestCoordinates (m p) (n p) → Fin (g p).L) := Grid.samples m n hm hn hnpos g hg have hw : a.Out (fun p q=>(gridWeight (g p) q).den) := (Grid.out_gridWeight m n hm hn hnpos g hg).map primrec_ratDen.to_comp have hh := @computable_prod P ℕ _ _ (fun p=>TestCoordinates (m p) (n p) → Fin (g p).L) _ a (fun _=>inferInstance) _ hw Primrec.nat_mul.to_comp apply hh.of_eq intro p unfold gridDenominator apply Finset.prod_congr (by ext; simp) intro q _ rfllemma c_budgetDenominator (b : P → Test → ℚ) (hb : (tests P).Out (fun p j=>b p j)) : Computable (fun p=>budgetDenominator (b p)) := computable_prod _ (hb.ratInv.map primrec_ratDen.to_comp) Primrec.nat_mul.to_compinclude ht hm hn hnpos hg inlemma c_innerDenominator (a : P → ℚ) (ha : Computable a) (b : P → Test → ℚ) (hb : (tests P).Out (fun p j=>b p j)) : Computable (fun p=>innerDenominator (t p) (m p) (n p) (g p) (a p) (b p)) := by exact ca_mul (ca_mul (ca_mul (ca_mul (ca_mul (ca_factorial (c_faceCardBound t m n ht hm hn hnpos)) (ca_factorial (c_faceCardBound t m n ht hm hn hnpos))) (computableCard (Face.codes m n hm hn hnpos))) (c_gridDenominator m n hm hn hnpos g hg)) (ca_pow (primrec_ratDen.to_comp.comp ha) (computableCard (Face.rows m n hm hn hnpos)))) (c_budgetDenominator b hb)end Denominator
open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate MinUncut.FiniteProof MinUncut.FiniteGaussianopen MinUncutGames.Foundations.Hastad.SourceOccurrences UEncodingnamespace UEncodingvariable {P : Type} [Primcodable P] {A B : P → Type}lemma map_testCases {c : UEncoding P A} {b : UEncoding P B} {j : ∀p,A p → Test} {f₁ f₂ f₃ f₄ : ∀p,A p → B p} (hj : c.Map (tests P) j) (h₁ : c.Map b f₁) (h₂ : c.Map b f₂) (h₃ : c.Map b f₃) (h₄ : c.Map b f₄) : c.Map b (fun p x=>match j p x with | .first => f₁ p x | .second => f₂ p x | .third => f₃ p x | .fourth => f₄ p x) := by have hq (k : Test) : c.Map bool (fun p x=>decide (j p x=k)) := map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun l=>decide (l=k)) hj apply (map_cond (hq .first) h₁ (map_cond (hq .second) h₂ (map_cond (hq .third) h₃ h₄))).ofEq intro p x cases j p x <;> rflend UEncodingnamespace Queriesvariable {P : Type} [Primcodable P]variable (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool)variable (hc : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (h p)).val))variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0<n p)def table := (Alphabet.labels t ht h hc).function (bool (P:=P))def queryEquiv (p : P) : Query (h p) ≃ Bool × (Alphabet (h p) → Bool) × (Alphabet (h p) → Bool) where toFun q := (q.first,q.left,q.right) invFun q := ⟨q.1,q.2.1,q.2.2⟩ left_inv _ := rfl right_inv _ := rfldef queries : UEncoding P (fun p=>Query (h p)) := (bool.prod ((table t ht h hc).prod (table t ht h hc))).ofEquiv (queryEquiv t h)lemma map_first : (queries t ht h hc).Map bool (fun _ q=>q.first) := by have hh:=map_comp (map_to (bool.prod ((table t ht h hc).prod (table t ht h hc))) (queryEquiv t h)) (map_fst _ _) exact hhlemma map_left : (queries t ht h hc).Map (table t ht h hc) (fun _ q=>q.left) := by 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 _ _) exact hhlemma map_right : (queries t ht h hc).Map (table t ht h hc) (fun _ q=>q.right) := by 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 _ _) exact hh
variable {Γ : P → Type} {c : UEncoding P Γ}variable {B C : ∀p,Γ p → FaceArray (Alphabet (h p)) (m p) (n p)}variable {z : ∀p,Γ p → Code (m p) (n p)} {s : ∀p,Γ p → ScoreIndex (m p) (n p) → Bool}variable {j : ∀p,Γ p → Test}variable (hB : c.Map (Alphabet.arrays t ht h hc m n hm hn hnpos) B)variable (hC : c.Map (Alphabet.arrays t ht h hc m n hm hn hnpos) C)variable (hz : c.Map (Face.codes m n hm hn hnpos) z)variable (hs : c.Map ((Grid.indices m n hm hn hnpos).function bool) s)variable (hj : c.Map (tests P) j)include hB hC hz hs hj inlemma map_leftEval {a : ∀p,Γ p → Alphabet (h p)} (ha : c.Map (Alphabet.labels t ht h hc) a) : 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 have hba := map_comp (map_pair hB ha) (Alphabet.map_labelCode t ht h hc m n hm hn hnpos) have hca := map_comp (map_pair hC ha) (Alphabet.map_labelCode t ht h hc m n hm hn hnpos) have hfalse : c.Map bool (fun _ _=>false) := map_const (Computable.const 0) have htrue : c.Map bool (fun _ _=>true) := map_const (Computable.const 1) have ha₀ := map_apply hs (map_pair hfalse hba) have ha₁ := map_apply hs (map_pair htrue hba) have ha₂ := map_apply hs (map_pair htrue hca) have ha₃ := map_cond (map_bool_eq hba hz) htrue ha₁ apply (map_testCases hj ha₀ ha₁ ha₃ ha₂).ofEq intro p x cases j p x <;> simp only [LocalTemplate.query] · change (if decide (labelCode (B p x) (a p x)=z p x) then true else _) = _ simp only [decide_eq_true_eq,Function.update_apply]include hB hC hz hs hj inlemma map_rightEval {a : ∀p,Γ p → Alphabet (h p)} (ha : c.Map (Alphabet.labels t ht h hc) a) : 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 have hba := map_comp (map_pair hB ha) (Alphabet.map_labelCode t ht h hc m n hm hn hnpos) have hca := map_comp (map_pair hC ha) (Alphabet.map_labelCode t ht h hc m n hm hn hnpos) have hfalse : c.Map bool (fun _ _=>false) := map_const (Computable.const 0) have htrue : c.Map bool (fun _ _=>true) := map_const (Computable.const 1) have ha₁ := map_apply hs (map_pair htrue hba) have ha₂ := map_apply hs (map_pair htrue hca) have ha₃ := map_cond (map_bool_eq hba hz) hfalse ha₁ apply (map_testCases hj ha₁ ha₂ ha₃ ha₂).ofEq intro p x cases j p x <;> simp only [LocalTemplate.query] · change (if decide (labelCode (B p x) (a p x)=z p x) then false else _) = _ simp only [decide_eq_true_eq,Function.update_apply]include hB hC hz hs hj inlemma map_query : c.Map (queries t ht h hc) (fun p x=>query (h p) (B p x) (C p x) (z p x) (s p x) (j p x)) := by 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 _ _)) 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 _ _)) 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 apply (map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun j=>decide (j=Test.fourth)) hj).ofEq intro p x cases j p x <;> rfl exact map_comp (map_pair hf (map_pair hl hr)) (map_from _ (queryEquiv t h))end Queriesend MinUncut.Preprocess
namespace MinUncut.Preprocess.Queriesopen MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate MinUncut.FiniteProof MinUncut.FiniteGaussianopen MinUncutGames.Foundations.Hastad.SourceOccurrences UEncodingvariable {P : Type} [Primcodable P]variable (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool)variable (hc : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (h p)).val))variable {Γ : P → Type} {c : UEncoding P Γ}variable {Q : ∀p,Γ p → Query (h p)} {pos : ∀p,Γ p → Fin (t p) → Fin 3}variable {sig : ∀p,Γ p → Signature (Fin (t p))} {x : ∀p,Γ p → Fin (t p) → Triple}variable (hQ : c.Map (queries t ht h hc) Q) (hp : c.Map (Alphabet.positionsList t ht) pos)variable (hs : c.Map (Alphabet.signatures t ht) sig)lemma zero_map : c.Map (Alphabet.labels t ht h hc) (fun _ _=>0) := by have hunit : c.Map (fixed Encoding.unit) (fun _ _=>()) := map_const (Computable.const 0) have hh := map_comp hunit (Alphabet.map_zeroLabel t ht h hc) exact hhinclude hQ hp hs inlemma map_leftBase : c.Map bool (fun p a=>(Q p a).leftBase (pos p a) (sig p a)) := by have hf:=map_comp hQ (map_first t ht h hc) have hl:=map_comp hQ (map_left t ht h hc) have ho:=map_comp hs (Alphabet.map_origin t ht) have hz:=map_comp (map_pair hp ho) (Alphabet.map_project t ht h hc) exact map_cond hf (map_apply hl hz) (map_apply hl (zero_map t ht h hc))include hQ hp hs inlemma map_leftTableEval (hx : c.Map (Alphabet.ambient t ht) x) : c.Map bool (fun p a=>(Q p a).leftTable (pos p a) (sig p a) (x p a)) := by have hf:=map_comp hQ (map_first t ht h hc) have hl:=map_comp hQ (map_left t ht h hc) have hv:=map_comp (map_pair hs hx) (Alphabet.map_valid t ht) have hproj:=map_comp (map_pair hp hx) (Alphabet.map_project t ht h hc) have hd:=map_comp hx (Alphabet.map_decode t ht h hc) have hfalse : c.Map bool (fun _ _=>false) := map_const (Computable.const 0) have hbase:=map_leftBase t ht h hc hQ hp hs have hzero:=map_apply hl (zero_map t ht h hc) apply (map_cond hf (map_cond hv (map_bool_eq hbase (map_apply hl hproj)) hfalse) (map_bool_eq hzero (map_apply hl hd))).ofEq intro p a simp only [Query.leftTable, Bool.beq_eq_decide_eq] split_ifs <;> simp_all only [decide_eq_true_eq, ite_true, ite_false]include hQ inlemma map_rightTableEval (hx : c.Map (Alphabet.ambient t ht) x) : c.Map bool (fun p a=>(Q p a).rightTable (x p a)) := by have hr:=map_comp hQ (map_right t ht h hc) have hd:=map_comp hx (Alphabet.map_decode t ht h hc) apply (map_bool_eq (map_apply hr (zero_map t ht h hc)) (map_apply hr hd)).ofEq intro p a simp only [Query.rightTable, Bool.beq_eq_decide_eq]include hQ hp hs inlemma map_localSign : c.Map bool (fun p a=>(Q p a).localSign (pos p a) (sig p a)) := by have hr:=map_comp hQ (map_right t ht h hc) apply (map_bool_eq (map_leftBase t ht h hc hQ hp hs) (map_apply hr (zero_map t ht h hc))).ofEq intro p a simp only [Query.localSign, Bool.beq_eq_decide_eq]include hQ hp hs inlemma map_leftTable : c.Map ((Alphabet.ambient t ht).function bool) (fun p a=>(Q p a).leftTable (pos p a) (sig p a)) := map_lambda (map_leftTableEval t ht h hc hQ.first hp.first hs.first (map_snd _ _))include hQ inlemma map_rightTable : c.Map ((Alphabet.ambient t ht).function bool) (fun p a=>(Q p a).rightTable) := map_lambda (map_rightTableEval t ht h hc hQ.first (map_snd _ _))end MinUncut.Preprocess.Queries
open scoped BigOperatorsnamespace MinUncut.Costed.SourceWordsopen MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplateopen MinUncutGames.Reduction MinUncut.SourceBridge
def signatureExpr (t : ℕ) : AExpr := AExpr.add (AExpr.sum (List.ofFn fun i : Fin t => AExpr.mul (AExpr.sum (List.ofFn fun p : Fin 3 => AExpr.mul (AExpr.sum (List.ofFn fun q : Fin 3 => AExpr.mul (.eq (slotExpr i.val p.val) (slotExpr i.val q.val)) (.const (2^q.val)))) (.const ((2^3)^p.val)))) (.const (((2^3)^3)^i.val)))) (.mul (.const (((2^3)^3)^t)) (.sum (List.ofFn fun i : Fin t=> .mul (slotExpr i.val 3) (.const (2^i.val)))))
lemma signatureExpr_eval {t : ℕ} (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) : (signatureExpr t).eval (inputTuple input u)= ((signatureEncoding t).code (signature (fun j=>equations input (u j)))).val := by rw [signature_code] simp only [signatureExpr,AExpr.eval,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn, slotExpr_name,slotExpr_rhs,signatureNumber,signature] congr 1 apply Finset.sum_congr rfl intro i _ congr 1 apply Finset.sum_congr rfl intro p _ congr 1 apply Finset.sum_congr rfl intro q _ congr 1 by_cases h : (equations input (u i)).names p=(equations input (u i)).names q · simp only [h,decide_true,Bool.toNat_true,ite_true] · have h' : ((equations input (u i)).names p).val≠((equations input (u i)).names q).val := fun e=>h (Fin.ext e) simp only [h,h',decide_false,Bool.toNat_false,ite_false]
def signatureLookup {t : ℕ} (f : Signature (Fin t) → ℕ) : AExpr := (signatureExpr t).lookup (constantTable (signatureEncoding t) f)lemma signatureLookup_eval {t : ℕ} (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) (f : Signature (Fin t) → ℕ) : (signatureLookup f).eval (inputTuple input u)=f (signature (fun j=>equations input (u j))) := by exact constantTable_eval _ _ _ _ _ (signatureExpr_eval input u)
end MinUncut.Costed.SourceWords
end
end OAI123456789101112131415161718192021222324252627import Mathlibimport OAI.Computability.MinUncut.Estimates.UniformRestrictimport OAI.Computability.MinUncut.Estimates.UniformTransport
namespace OAI
sectionnamespace MinUncut.Preprocess.UEncodingvariable {P Q : Type} [Primcodable P] [Primcodable Q] {A : P → Type} {X : Type} [Primcodable X]lemma Out.pullback {a : UEncoding P A} {g : ∀p,A p → X} (hg : a.Out g) {f : Q → P} (hf : Computable f) : (a.pullback f hf).Out (fun q x=>g (f q) x) := by obtain ⟨g',hgr,hg⟩:=hg exact ⟨fun q=>g' (f q.1,q.2),hgr.comp ((hf.comp Computable.fst).pair Computable.snd), by intro q x; exact hg (f q) x⟩lemma Out.cons {a : UEncoding P A} {f : ∀p,A p → X} {g : ∀p,A p → List X} (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>f p x::g p x) := hf.map₂ hg Primrec.list_cons.to_complemma out_boolNat {a : UEncoding P A} {f : ∀p,A p → Bool} (hf : a.Map bool f) : a.Out (fun p x=>(f p x).toNat) := (hf.out false).map (Primrec.dom_bool Bool.toNat).to_compend MinUncut.Preprocess.UEncoding
end
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import Mathlibimport OAI.Computability.MinUncut.Estimates.UniformRestrict
namespace OAI
sectionnamespace MinUncut.Preprocessopen MinUncutGames.Foundations.Hastad.SourceOccurrencesopen scoped BigOperatorsvariable {P X : Type} [Primcodable P] [Primcodable X] [CommMonoid X]lemma c_rangeProd {f : P → ℕ → X} (hf : Computable₂ f) (hmul : Computable₂ (fun x y : X=>x*y)) : Computable₂ (fun p n=>((List.range n).map (f p)).prod) := by have hh := Computable.nat_rec (α:=P × ℕ) (σ:=X) Computable.snd (Computable.const 1) (hmul.comp (Computable.snd.comp Computable.snd) (hf.comp (Computable.fst.comp Computable.fst) (Computable.fst.comp Computable.snd))).to₂ exact hh.of_eq (by intro p induction p.2 with | zero => rfl | succ n ih => simp only [List.range_succ,List.map_append,List.map_singleton,List.prod_append, List.prod_singleton,ih])
namespace UEncodingvariable {A B Γ : P → Type}lemma out_prod {g : UEncoding P Γ} {a : UEncoding P A} [∀p,Fintype (A p)] {f : ∀p,Γ p × A p → X} (hf : (g.prod a).Out f) (hmul : Computable₂ (fun x y : X=>x*y)) : g.Out (fun p s=>∏x,f p (s,x)) := by obtain ⟨f',hf',hf⟩:=hf let raw : (P × ℕ) → ℕ → X := fun q i=>f' (q.1,q.2*(a.enc q.1).size+i) have hr : Computable₂ raw := by unfold raw exact hf'.comp ((Computable.fst.comp Computable.fst).pair (ca_add (ca_mul (Computable.snd.comp Computable.fst) (a.computableSize.comp (Computable.fst.comp Computable.fst))) Computable.snd)) refine ⟨fun q=>((List.range (a.enc q.1).size).map (raw q)).prod, (c_rangeProd hr hmul).comp Computable.id (a.computableSize.comp Computable.fst),?_⟩ intro p s dsimp only have he : ((a.enc p).enumerate.map (fun x=>f p (s,x))).prod=∏x,f p (s,x) := by classical have ht : (a.enc p).enumerate.toFinset=Finset.univ := by ext x; simp [(a.enc p).mem_enumerate x] rw [← List.prod_toFinset _ (a.enc p).nodup_enumerate,ht] rw [←he,Encoding.enumerate,List.ofFn_eq_map,List.map_map] rw [←finRange_values ((a.enc p).size),List.map_map] apply congrArg List.prod apply List.map_congr_left intro i hi have hh:=hf p (s,(a.enc p).code.symm i) change f' (p,(((g.enc p).prod (a.enc p)).code (s,(a.enc p).code.symm i)).val)=_ at hh rw [prod_code,Equiv.apply_symm_apply] at hh exact hh
omit [Primcodable X] [CommMonoid X] inlemma computableCard (a : UEncoding P A) [∀p,Fintype (A p)] : Computable (fun p=>Fintype.card (A p)) := a.computableSize.of_eq (fun p=>(Fintype.card_congr (a.enc p).code).trans (Fintype.card_fin _)|>.symm)
end UEncodingend MinUncut.Preprocess
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195import Mathlibimport OAI.Computability.MinUncut.Estimates.UniformBoolean
namespace OAI
namespace MinUncut.Preprocessopen MinUncutGames.Foundations.Hastad.SourceOccurrencesnamespace UEncodingvariable {P : Type} [Primcodable P] {A B Γ : P → Type}
def goodCodes (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) : List ℕ := (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)lemma goodCodes_nodup (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) : (goodCodes a b p).Nodup := List.nodup_range.filter _lemma mem_goodCodes (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) (n : ℕ) : n∈goodCodes a b p ↔ ∃h:n<(a.enc p).size,b p ((a.enc p).code.symm ⟨n,h⟩)=true := by simp only [goodCodes,List.mem_filter,List.mem_range] by_cases hn:n<(a.enc p).size <;> simp [hn]lemma original_mem_goodCodes (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) (x : A p) : ((a.enc p).code x).val∈goodCodes a b p ↔ b p x=true := by rw [mem_goodCodes] simp only [Equiv.symm_apply_apply,Fin.eta] exact ⟨fun h=>h.2,fun h=>⟨((a.enc p).code x).isLt,h⟩⟩
lemma computable_goodCodes (a : UEncoding P A) (b : ∀p,A p → Bool) (hb : a.Map bool b) : Computable (goodCodes a b) := by obtain ⟨f,hf,h⟩:=hb have hr : Computable₂ (fun p n=>if f (p,n)=1 then [n] else []) := by exact (Computable.cond (Primrec.eq.decide.to_comp.comp hf (Computable.const 1)) (Computable.list_cons.comp Computable.snd (Computable.const [])) (Computable.const [])).of_eq (by intro q; simp) have hh := Primrec.list_flatten.to_comp.comp ((c_rangeMap hr).comp Computable.id a.computableSize) apply hh.of_eq intro p change (List.range (a.enc p).size).flatMap _=_ rw [show goodCodes a b p=(List.range (a.enc p).size).flatMap (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 unfold goodCodes generalize List.range (a.enc p).size = xs induction xs with | nil => rfl | cons x xs ih => simp only [List.filter_cons,List.flatMap_cons,ih]; split_ifs <;> simp_all] apply List.flatMap_congr intro n hn have hn' : n<(a.enc p).size := List.mem_range.mp hn have ht := h p ((a.enc p).code.symm ⟨n,hn'⟩) simp only [Equiv.apply_symm_apply] at ht dsimp only [id] simp only [dite_eq_left hn',ht] change (if (Encoding.bool.code _).val=1 then _ else _) = _ rw [bool_code] cases b p ((a.enc p).code.symm ⟨n,hn'⟩) <;> rfl
def restrictEquiv (a : UEncoding P A) (b : ∀p,A p → Bool) (p : P) : {x:A p // b p x=true} ≃ {n:ℕ // n∈goodCodes a b p} where toFun x := ⟨((a.enc p).code x.val).val,(original_mem_goodCodes a b p x).mpr x.property⟩ invFun n := ⟨(a.enc p).code.symm ⟨n.val,((mem_goodCodes a b p n).mp n.property).choose⟩, ((mem_goodCodes a b p n).mp n.property).choose_spec⟩ left_inv x := by apply Subtype.ext; exact (a.enc p).code.symm_apply_apply x.val right_inv n := by apply Subtype.ext; exact congrArg Fin.val ((a.enc p).code.apply_symm_apply _)
def restrict (a : UEncoding P A) (b : ∀p,A p → Bool) (hb : a.Map bool b) : UEncoding P (fun p=>{x:A p // b p x=true}) where enc p := ⟨(goodCodes a b p).length,(restrictEquiv a b p).trans ((goodCodes_nodup a b p).getEquiv (goodCodes a b p)).symm⟩ computableSize := Computable.list_length.comp (computable_goodCodes a b hb)
lemma restrict_code (a : UEncoding P A) (b : ∀p,A p → Bool) (hb : a.Map bool b) (p : P) (x : {x:A p // b p x=true}) : (((a.restrict b hb).enc p).code x).val=(goodCodes a b p).idxOf (((a.enc p).code x.val).val) := rfl
lemma map_restrict_val (a : UEncoding P A) (b : ∀p,A p → Bool) (hb : a.Map bool b) : (a.restrict b hb).Map a (fun _ x=>x.val) := by refine ⟨fun q=>((goodCodes a b q.1)[q.2]?).getD 0,?_,?_⟩ · exact Primrec.option_getD_default.to_comp.comp (Computable.list_getElem?.comp ((computable_goodCodes a b hb).comp Computable.fst) Computable.snd) · intro p x dsimp only rw [restrict_code,List.getElem?_idxOf (by exact (original_mem_goodCodes a b p x).mpr x.property)] rfl
lemma map_restrict_mk {g : UEncoding P Γ} {a : UEncoding P A} {b : ∀p,A p → Bool} (hb : a.Map bool b) {f : ∀p,Γ p → A p} (hf : g.Map a f) (h : ∀p x,b p (f p x)=true) : g.Map (a.restrict b hb) (fun p x=>⟨f p x,h p x⟩) := by obtain ⟨f',hf',he⟩:=hf refine ⟨fun q=>(goodCodes a b q.1).idxOf (f' q),?_,?_⟩ · exact Primrec.list_idxOf.to_comp.comp hf' ((computable_goodCodes a b hb).comp Computable.fst) · intro p x dsimp only rw [he,restrict_code]
end UEncoding
namespace UEncodingvariable {P : Type} [Primcodable P] {A B Γ : P → Type}variable {X Y Z : Type} [Primcodable X] [Primcodable Y] [Primcodable Z]
def Out (a : UEncoding P A) (f : ∀p,A p → X) : Prop := ∃g : P × ℕ → X, Computable g ∧ ∀p x,g (p,((a.enc p).code x).val)=f p xlemma Out.ofEq {a : UEncoding P A} {f g : ∀p,A p → X} (hf : a.Out f) (h : ∀p x,f p x=g p x) : a.Out g := by obtain ⟨f',hr,hh⟩:=hf exact ⟨f',hr,fun p x=>(hh p x).trans (h p x)⟩lemma out_const (a : UEncoding P A) {f : P → X} (hf : Computable f) : a.Out (fun p _=>f p) := ⟨_,hf.comp Computable.fst,by intros; rfl⟩lemma out_code (a : UEncoding P A) : a.Out (fun p x=>((a.enc p).code x).val) := ⟨Prod.snd,Computable.snd,by intros; rfl⟩lemma Out.comp {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,A p → B p} {g : ∀p,B p → X} (hg : b.Out g) (hf : a.Map b f) : a.Out (fun p x=>g p (f p x)) := by obtain ⟨f',hrf,hf⟩:=hf obtain ⟨g',hrg,hg⟩:=hg exact ⟨fun q=>g' (q.1,f' q),hrg.comp (Computable.fst.pair hrf), by intro p x; dsimp only; rw [hf,hg]⟩lemma Out.map {a : UEncoding P A} {f : ∀p,A p → X} (hf : a.Out f) {g : X → Y} (hg : Computable g) : a.Out (fun p x=>g (f p x)) := by obtain ⟨f',hrf,hf⟩:=hf exact ⟨_,hg.comp hrf,by intro p x; dsimp only; rw [hf]⟩lemma Out.map₂ {a : UEncoding P A} {f : ∀p,A p → X} {g : ∀p,A p → Y} (hf : a.Out f) (hg : a.Out g) {op : X → Y → Z} (hop : Computable₂ op) : a.Out (fun p x=>op (f p x) (g p x)) := by obtain ⟨f',hrf,hf⟩:=hf obtain ⟨g',hrg,hg⟩:=hg exact ⟨_,hop.comp hrf hrg,by intro p x; dsimp only; rw [hf,hg]⟩lemma Out.pair {a : UEncoding P A} {f : ∀p,A p → X} {g : ∀p,A p → Y} (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>(f p x,g p x)) := hf.map₂ hg (Computable.fst.pair Computable.snd)lemma Out.first {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,A p → X} (hf : a.Out f) : (a.prod b).Out (fun p x=>f p x.1) := hf.comp (map_fst a b)lemma Out.second {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,A p → X} (hf : a.Out f) : (b.prod a).Out (fun p x=>f p x.2) := hf.comp (map_snd b a)
lemma out_list {g : UEncoding P Γ} {a : UEncoding P A} {f : ∀p,Γ p × A p → X} (hf : (g.prod a).Out f) : g.Out (fun p s=>(a.enc p).enumerate.map (fun x=>f p (s,x))) := by obtain ⟨f',hf',hf⟩:=hf let raw : (P × ℕ) → ℕ → X := fun q i=>f' (q.1,q.2*(a.enc q.1).size+i) have hr : Computable₂ raw := by unfold raw exact hf'.comp ((Computable.fst.comp Computable.fst).pair (ca_add (ca_mul (Computable.snd.comp Computable.fst) (a.computableSize.comp (Computable.fst.comp Computable.fst))) Computable.snd)) refine ⟨fun q=>(List.range (a.enc q.1).size).map (raw q), (c_rangeMap hr).comp Computable.id (a.computableSize.comp Computable.fst),?_⟩ intro p s dsimp only rw [Encoding.enumerate,List.ofFn_eq_map,List.map_map] rw [←finRange_values ((a.enc p).size),List.map_map] apply List.map_congr_left intro i hi have hh:=hf p (s,(a.enc p).code.symm i) change f' (p,(((g.enc p).prod (a.enc p)).code (s,(a.enc p).code.symm i)).val)=_ at hh rw [prod_code,Equiv.apply_symm_apply] at hh exact hh
lemma Out.enumerate {a : UEncoding P A} {f : ∀p,A p → X} (hf : a.Out f) : Computable (fun p=>(a.enc p).enumerate.map (f p)) := by have hh:=out_list (g:=fixed Encoding.unit) hf.second obtain ⟨h,hr,he⟩:=hh exact (hr.comp (Computable.id.pair (Computable.const 0))).of_eq (fun p=>he p ())
lemma fixed_out (a : Encoding X) (x₀ : X) : (fixed (P:=P) a).Out (fun _ x=>x) := by let table:=a.enumerate refine ⟨fun q=>(table[q.2]?).getD x₀,?_,?_⟩ · exact Primrec.option_getD.to_comp.comp ((Primrec.list_getElem?₁ table).to_comp.comp Computable.snd) (Computable.const x₀) · intro p x dsimp only change (a.enumerate[(a.code x).val]?).getD x₀=x simp [Encoding.enumerate,(a.code x).isLt]lemma Map.out {a : UEncoding P A} {b : Encoding X} {f : ∀p,A p → X} (hf : a.Map (fixed b) f) (x₀ : X) : a.Out f := (fixed_out b x₀).comp hflemma Out.toBool {a : UEncoding P A} {f : ∀p,A p → Bool} (hf : a.Out f) : a.Map bool f := by obtain ⟨f',hr,h⟩:=hf refine ⟨fun q=>(f' q).toNat,(Primrec.dom_bool Bool.toNat).to_comp.comp hr,?_⟩ intro p x dsimp only rw [h] exact (bool_code _).symmlemma Out.toFin {a : UEncoding P A} {n : P → ℕ} (hn : Computable n) {f : ∀p,A p → Fin (n p)} (hf : a.Out (fun p x=>(f p x).val)) : a.Map (fin n hn) f := hflemma Out.cond {a : UEncoding P A} {c : ∀p,A p → Bool} {f g : ∀p,A p → X} (hc : a.Map bool c) (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>if c p x then f p x else g p x) := by obtain ⟨c',hcr,hc⟩:=hc.out false obtain ⟨f',hfr,hf⟩:=hf obtain ⟨g',hgr,hg⟩:=hg exact ⟨_,Computable.cond hcr hfr hgr,by intro p x; simp only [hc,hf,hg,Bool.cond_eq_ite]⟩
end UEncodingend MinUncut.Preprocess
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import Mathlibimport OAI.Computability.MinUncut.Estimates.UniformAlgebraimport OAI.Computability.MinUncut.Encoding.DerivedResolverimport OAI.Computability.MinUncut.Estimates.UniformOutput
namespace OAI
sectionnoncomputable sectionnamespace MinUncut.Preprocessopen MinUncut.Outer MinUncutGames.Foundations.Hastad.SourceOccurrences UEncodingopen scoped BigOperatorsdef maskEquiv (t : ℕ) : Finset (Fin t) ≃ (Fin t → Bool) where toFun := hiddenSet invFun h := Finset.univ.filter (fun i=>h i=true) left_inv S := by ext i; simp [hiddenSet] right_inv h := by funext i; simp [hiddenSet]def setEncoding (t : ℕ) : Encoding (Finset (Fin t)) := ⟨2^t,(maskEquiv t).trans (((Encoding.fin t).function Encoding.bool).code)⟩def rawSet (t z : ℕ) : Finset (Fin t) := (setEncoding t).code.symm ⟨z%(2^t),Nat.mod_lt _ (pow_pos (by decide) _)⟩lemma rawSet_code (t : ℕ) (S : Finset (Fin t)) : rawSet t ((setEncoding t).code S).val=S := by unfold rawSet have hs : ((setEncoding t).code S).val<2^t := ((setEncoding t).code S).isLt simp only [Nat.mod_eq_of_lt hs] exact (setEncoding t).code.symm_apply_apply Slemma rawSet_maskCode (t z : ℕ) : (((Encoding.fin t).function Encoding.bool).code (hiddenSet (rawSet t z))).val=z%(2^t) := by change ((setEncoding t).code ((setEncoding t).code.symm _)).val=_ rw [Equiv.apply_symm_apply]variable {P : Type} [Primcodable P]def sets (t : P → ℕ) (ht : Computable t) : UEncoding P (fun p=>Finset (Fin (t p))) where enc p := setEncoding (t p) computableSize := ca_pow (ca_const 2) htlemma map_hidden (t : P → ℕ) (ht : Computable t) : (sets t ht).Map ((fin t ht).function bool) (fun _ S=>hiddenSet S) := ⟨Prod.snd,Computable.snd,by intros; rfl⟩lemma out_setCard (t : P → ℕ) (ht : Computable t) : (sets t ht).Out (fun _ S=>S.card) := by have hmask:=map_hidden t ht have hi := map_apply hmask.first (map_snd (sets t ht) (fin t ht)) apply (out_sum (out_boolNat hi) Primrec.nat_add.to_comp).ofEq intro p S have he : ∀i:Fin (t p), (hiddenSet S i).toNat=if i∈S then 1 else 0 := by intro i by_cases hi:i∈S <;> simp [hiddenSet,hi] simp only [he] simplemma c_rawHidden (t : P → ℕ) (ht : Computable t) (z : P → ℕ) (hz : Computable z) : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (hiddenSet (rawSet (t p) (z p)))).val) := (ca_mod hz (ca_pow (ca_const 2) ht)).of_eq (by intro p; exact (rawSet_maskCode _ _).symm)end MinUncut.Preprocess
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119import Mathlibimport OAI.Computability.MinUncut.Encoding.UniformEncoding
namespace OAI
namespace MinUncut.Preprocessopen MinUncutGames.Foundations.Hastad.SourceOccurrencesnamespace UEncodingvariable {P Q : Type} [Primcodable P] [Primcodable Q] {A B C Γ : P → Type}
def ofEquiv (a : UEncoding P A) (e : ∀p,B p ≃ A p) : UEncoding P B where enc p := ⟨(a.enc p).size,(e p).trans (a.enc p).code⟩ computableSize := a.computableSizelemma map_to (a : UEncoding P A) (e : ∀p,B p ≃ A p) : (a.ofEquiv e).Map a (fun p x=>e p x) := ⟨Prod.snd,Computable.snd,by intros; rfl⟩lemma map_from (a : UEncoding P A) (e : ∀p,B p ≃ A p) : a.Map (a.ofEquiv e) (fun p x=>(e p).symm x) := ⟨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⟩
def pullback (a : UEncoding P A) (f : Q → P) (hf : Computable f) : UEncoding Q (fun q=>A (f q)) where enc q := a.enc (f q) computableSize := a.computableSize.comp hflemma Map.pullback {a : UEncoding P A} {b : UEncoding P B} {g : ∀p,A p → B p} (hg : a.Map b g) {f : Q → P} (hf : Computable f) : (a.pullback f hf).Map (b.pullback f hf) (fun q x=>g (f q) x) := by obtain ⟨g',hg',hg⟩:=hg refine ⟨fun q=>g' (f q.1,q.2),hg'.comp ((hf.comp Computable.fst).pair Computable.snd),?_⟩ intro q x exact hg (f q) x
lemma Map.first {a : UEncoding P A} {b : UEncoding P B} {c : UEncoding P C} {f : ∀p,A p → B p} (hf : a.Map b f) : (a.prod c).Map b (fun p x=>f p x.1) := map_comp (map_fst a c) hflemma Map.second {a : UEncoding P A} {b : UEncoding P B} {c : UEncoding P C} {f : ∀p,A p → B p} (hf : a.Map b f) : (c.prod a).Map b (fun p x=>f p x.2) := map_comp (map_snd c a) hf
lemma Map.specialize {g : UEncoding P Γ} {a : UEncoding P A} {b : UEncoding P B} {f : ∀p,Γ p × A p → B p} (hf : (g.prod a).Map b f) {x : ∀p,Γ p → A p} (hx : g.Map a x) : g.Map b (fun p s=>f p (s,x p s)) := map_comp (map_pair (map_id g) hx) hf
end UEncoding
namespace UEncodingvariable {P : Type} [Primcodable P] {A B C Γ : P → Type}variable {p : P}def sum (a : UEncoding P A) (b : UEncoding P B) : UEncoding P (fun p=>A p ⊕ B p) where enc p := (a.enc p).sum (b.enc p) computableSize := ca_add a.computableSize b.computableSizeomit [Primcodable P] inlemma sum_code_inl (a : Encoding (A p)) (b : Encoding (B p)) (x : A p) : ((a.sum b).code (Sum.inl x)).val=(a.code x).val := rflomit [Primcodable P] inlemma sum_code_inr (a : Encoding (A p)) (b : Encoding (B p)) (x : B p) : ((a.sum b).code (Sum.inr x)).val=a.size+(b.code x).val := rfllemma map_inl (a : UEncoding P A) (b : UEncoding P B) : a.Map (a.sum b) (fun _ x=>Sum.inl x) := ⟨Prod.snd, Computable.snd, by intro p x; rfl⟩lemma map_inr (a : UEncoding P A) (b : UEncoding P B) : b.Map (a.sum b) (fun _ x=>Sum.inr x) := ⟨fun q=>(a.enc q.1).size+q.2, ca_add (a.computableSize.comp Computable.fst) Computable.snd, by intro p x; rfl⟩lemma map_case {g : UEncoding P Γ} {a : UEncoding P A} {b : UEncoding P B} {c : UEncoding P C} {f : ∀p,Γ p × A p → C p} {h : ∀p,Γ p × B p → C p} (hf : (g.prod a).Map c f) (hh : (g.prod b).Map c h) : (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 obtain ⟨f',hf',hf⟩:=hf obtain ⟨h',hh',hh⟩:=hh let leftSize : P × ℕ → ℕ := fun q=>(a.enc q.1).size let rightSize : P × ℕ → ℕ := fun q=>(b.enc q.1).size let tag : P × ℕ → ℕ := fun q=>q.2 % (leftSize q+rightSize q) let ctxt : P × ℕ → ℕ := fun q=>q.2 / (leftSize q+rightSize q) have hl : Computable leftSize := a.computableSize.comp Computable.fst have hr : Computable rightSize := b.computableSize.comp Computable.fst have ht : Computable tag := ca_mod Computable.snd (ca_add hl hr) have hc : Computable ctxt := ca_div Computable.snd (ca_add hl hr) let raw : P × ℕ → ℕ := fun q=>if tag q<leftSize q then f' (q.1,ctxt q*leftSize q+tag q) else h' (q.1,ctxt q*rightSize q+(tag q-leftSize q)) have hraw : Computable raw := (Computable.cond (ca_natLt ht hl).decide (hf'.comp (Computable.fst.pair (ca_add (ca_mul hc hl) ht))) (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]) refine ⟨raw,hraw,?_⟩ intro p ⟨s,z⟩ have hz : (((a.enc p).sum (b.enc p)).code z).val<(a.enc p).size+(b.enc p).size := (((a.enc p).sum (b.enc p)).code z).isLt have hs : 0<(a.enc p).size+(b.enc p).size := by exact Nat.zero_lt_of_lt hz 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 simp only [ctxt,leftSize,rightSize] 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)/ ((a.enc p).size+(b.enc p).size)=_ rw [Nat.add_mul_div_left _ _ hs,Nat.div_eq_of_lt hz,Nat.zero_add] 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 simp only [tag,leftSize,rightSize] 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)% ((a.enc p).size+(b.enc p).size)=_ rw [Nat.add_mul_mod_self_left,Nat.mod_eq_of_lt hz] change raw (p,(((g.enc p).prod ((a.enc p).sum (b.enc p))).code (s,z)).val)=_ dsimp only [raw] rw [hc',ht'] cases z with | inl x => have he:=hf p (s,x) change f' (p,(((g.enc p).prod (a.enc p)).code (s,x)).val)=_ at he rw [prod_code] at he simpa only [show (((a.enc p).sum (b.enc p)).code (.inl x)).val=((a.enc p).code x).val from rfl, leftSize,rightSize,((a.enc p).code x).isLt,ite_true,Sum.elim_inl] using he | inr x => have he:=hh p (s,x) change h' (p,(((g.enc p).prod (b.enc p)).code (s,x)).val)=_ at he rw [prod_code] at he 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, leftSize,rightSize,Nat.add_sub_cancel_left,Nat.not_lt.mpr (Nat.le_add_right _ _),ite_false,Sum.elim_inr] using heend UEncodingend MinUncut.Preprocess
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187import Mathlibimport OAI.Computability.MinUncut.Search.FiniteAverageBoundsimport OAI.Computability.MinUncut.Estimates.LiteralTestQueriesimport OAI.Computability.MinUncut.Analysis.RationalRowNoise
namespace OAI
noncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProofattribute [local instance] Classical.propDecidable coordsDecEqvariable {Name I : Type*} [Fintype I] {m n : ℕ}
abbrev LocalSample (A : Type*) {V : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] (m n : ℕ) (g : GridData) := FaceArray A m n × FaceArray A m n × Code m n × (TestCoordinates m n → Fin g.L)
def noiseWeight {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] (a : ℚ) (B C : FaceArray A m n) : Test → ℚ | .second => RowNoise.rationalDensity a B C | _ => 1
def localWeight {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] (g : GridData) (a b : ℚ) (j : Test) (p : LocalSample A m n g) : ℚ := (Fintype.card (FaceArray A m n):ℚ)⁻¹ * (Fintype.card (FaceArray A m n):ℚ)⁻¹ * (Fintype.card (Code m n):ℚ)⁻¹ * gridWeight g p.2.2.2 * noiseWeight a p.1 p.2.1 j / b
lemma sum_invcard_mul {X : Type*} [Fintype X] (f : X → ℝ) : (∑ x, (Fintype.card X:ℝ)⁻¹*f x)=𝔼 x, f x := by rw [← Finset.mul_sum,Fintype.expect_eq_sum_div_card,mul_comm,div_eq_mul_inv]
lemma localWeight_nonneg {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] (g : GridData) (hT : 0<g.T) (hL : 0<g.L) {a b : ℚ} (ha : 0≤a) (ha1 : a≤1) (hb : 0<b) (j : Test) (p : LocalSample A m n g) : 0≤localWeight g a b j p := by have hg := (gridWeight_pos g hT hL p.2.2.2).le have hn : 0≤noiseWeight a p.1 p.2.1 j := by cases j with | second => exact RowNoise.rationalDensity_nonneg ha ha1 _ _ | first => exact zero_le_one | third => exact zero_le_one | fourth => exact zero_le_one exact div_nonneg (mul_nonneg (mul_nonneg (mul_nonneg (mul_nonneg (inv_nonneg.mpr (Nat.cast_nonneg _)) (inv_nonneg.mpr (Nat.cast_nonneg _))) (inv_nonneg.mpr (Nat.cast_nonneg _))) hg) hn) hb.le
lemma localWeight_sum {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] (g : GridData) (a b : ℚ) (j : Test) (F : LocalSample A m n g → ℝ) : (∑ p, (localWeight g a b j p:ℝ)*F p)= (𝔼 B, 𝔼 C, 𝔼 z, ∑ q : TestCoordinates m n → Fin g.L, (gridWeight g q:ℝ)*(noiseWeight a B C j:ℝ)*F (B,C,z,q))/(b:ℝ) := by simp only [localWeight,Rat.cast_div,Rat.cast_mul,Rat.cast_inv,Rat.cast_natCast, Fintype.sum_prod_type,Fintype.expect_eq_sum_div_card] simp only [div_eq_mul_inv,Finset.sum_mul] apply Finset.sum_congr rfl intro B _ apply Finset.sum_congr rfl intro C _ apply Finset.sum_congr rfl intro z _ apply Finset.sum_congr rfl intro q _ ring
lemma noiseWeight_cast (U : I → Equation Name) (h : I → Bool) (pos : I → Fin 3) (a : ℚ) (B C : FaceArray (SecondAlphabet (secondQuestion U h pos)) m n) : (noiseWeight a B C .second:ℝ)=RowNoise.density a B C := RowNoise.rationalDensity_cast a B C
lemma localTest_mean (f : ProofFamily Name I) (U : I → Equation Name) (h : I → Bool) (pos : I → Fin 3) (g : GridData) (a σ η : ℚ) (j : Test) : (𝔼 B, 𝔼 C, 𝔼 z, ∑ q : TestCoordinates m n → Fin g.L, (gridWeight g q:ℝ)*(noiseWeight a B C j:ℝ)* testFunctional f U h pos B C z (rationalScoreTable σ η (fun i => midpoint g.T g.L (q i))) j)= match j with | .first => finiteFirst (m := m) (n := n) g (f.second (secondQuestion U h pos)) σ η | .second => finiteSecond (m := m) (n := n) g (f.second (secondQuestion U h pos)) a σ η | .third => finiteThird (m := m) (n := n) g (f.second (secondQuestion U h pos)) σ η | .fourth => finiteFourth (m := m) (n := n) g (projection U h pos) (f.first U) (f.second (secondQuestion U h pos)) σ η := by cases j · simp only [noiseWeight,Rat.cast_one,mul_one,testFunctional,Fintype.expect_const, finiteFirst,tableAverage] · simp only [noiseWeight,RowNoise.rationalDensity_cast,testFunctional,Fintype.expect_const, finiteSecond,tableAverage] congr 1 funext B congr 1 funext C rw [Finset.mul_sum] exact Finset.sum_congr rfl (fun q _ => by ring) · simp only [noiseWeight,Rat.cast_one,mul_one,testFunctional,Fintype.expect_const, finiteThird,tableAverage] · simp only [noiseWeight,Rat.cast_one,mul_one,testFunctional,Fintype.expect_const, finiteFourth,tableAverage]end MinUncut.Outer
namespace MinUncut.Outeropen MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothnessattribute [local instance] Classical.propDecidable coordsDecEqvariable {Name I S : Type*} [Fintype I] [Fintype S] {m n k : ℕ}
instance localSampleFintype {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] (m n : ℕ) (g : GridData) : Fintype (LocalSample A m n g) := by unfold LocalSample infer_instance
abbrev OuterSample (I S : Type*) [Fintype I] (k : ℕ) := FixedSets I k × (I → S) × (I → Fin 3)
def sampleFirst (equations : S → Equation Name) (o : OuterSample I S k) : I → Equation Name := fun i => equations (o.2.1 i)def sampleHidden (o : OuterSample I S k) : I → Bool := hiddenSet o.1.val
abbrev sampleSecond (equations : S → Equation Name) (o : OuterSample I S k) : I → SecondQuestion Name := secondQuestion (sampleFirst equations o) (sampleHidden o) o.2.2
abbrev Elementary (equations : S → Equation Name) (k m n : ℕ) (g : GridData) := Σ o : OuterSample I S k, LocalSample (SecondAlphabet (sampleSecond equations o)) m n g
instance elementaryFintype (equations : S → Equation Name) (k m n : ℕ) (g : GridData) : Fintype (Elementary (I := I) equations k m n g) := by unfold Elementary infer_instance
def elementaryWeight (equations : S → Equation Name) (g : GridData) (a b : ℚ) (j : Test) (e : Elementary (I := I) equations k m n g) : ℚ := (Fintype.card (OuterSample I S k):ℚ)⁻¹*localWeight g a b j e.2
def elementaryQuery (equations : S → Equation Name) (g : GridData) (σ η : ℚ) (j : Test) (e : Elementary (I := I) equations k m n g) : QueryDemand (A := FamilyAlphabet (Name := Name) (I := I)) := testQuery (sampleFirst equations e.1) (sampleHidden e.1) e.1.2.2 e.2.1 e.2.2.1 e.2.2.2.1 (rationalScoreTable σ η (fun i => midpoint g.T g.L (e.2.2.2.2 i))) j
lemma elementaryWeight_nonneg (equations : S → Equation Name) (g : GridData) (hT : 0<g.T) (hL : 0<g.L) {a b : ℚ} (ha : 0≤a) (ha1 : a≤1) (hb : 0<b) (j : Test) (e : Elementary (I := I) equations k m n g) : 0≤elementaryWeight equations g a b j e := mul_nonneg (inv_nonneg.mpr (Nat.cast_nonneg _)) (localWeight_nonneg g hT hL ha ha1 hb j e.2)
lemma expect_prod_type {X Y : Type*} [Fintype X] [Fintype Y] (f : X × Y → ℝ) : (𝔼 p, f p)=𝔼 x, 𝔼 y, f (x,y) := by simp only [Fintype.expect_eq_sum_div_card,Fintype.sum_prod_type,Fintype.card_prod,Nat.cast_mul, Finset.sum_div,div_div] rw [mul_comm (Fintype.card X:ℝ)]
lemma outer_weight_sum (equations : S → Equation Name) (F : EdgeStatistic Name I) : (∑ o : OuterSample I S k, (Fintype.card (OuterSample I S k):ℝ)⁻¹* F (sampleFirst equations o) (sampleHidden o) o.2.2)=edgeMean equations k F := by rw [sum_invcard_mul,expect_prod_type] simp only [expect_prod_type,edgeMean,sampleHidden] rfl
lemma elementary_weighted_sum (equations : S → Equation Name) (g : GridData) (a b σ η : ℚ) (j : Test) (f : ProofFamily Name I) : (∑ e : Elementary (I := I) equations k m n g, (elementaryWeight equations g a b j e:ℝ)*((elementaryQuery equations g σ η j e).failure f.queryAnswer:ℝ))= edgeMean equations k (fun U h pos => (match j with | .first => finiteFirst (m := m) (n := n) g (f.second (secondQuestion U h pos)) σ η | .second => finiteSecond (m := m) (n := n) g (f.second (secondQuestion U h pos)) a σ η | .third => finiteThird (m := m) (n := n) g (f.second (secondQuestion U h pos)) σ η | .fourth => finiteFourth (m := m) (n := n) g (projection U h pos) (f.first U) (f.second (secondQuestion U h pos)) σ η)/(b:ℝ)) := by change (∑ e : Sigma _, _) = _ rw [Fintype.sum_sigma] simp only [elementaryWeight,Rat.cast_mul,Rat.cast_inv,Rat.cast_natCast,mul_assoc,← Finset.mul_sum] trans ∑ o : OuterSample I S k, (Fintype.card (OuterSample I S k):ℝ)⁻¹* ((𝔼 B, 𝔼 C, 𝔼 z, ∑ q : TestCoordinates m n → Fin g.L, (gridWeight g q:ℝ)*(noiseWeight a B C j:ℝ)*testFunctional f (sampleFirst equations o) (sampleHidden o) o.2.2 B C z (rationalScoreTable σ η (fun i => midpoint g.T g.L (q i))) j)/(b:ℝ)) · rw [Finset.mul_sum] apply Finset.sum_congr rfl intro o _ congr 1 rw [localWeight_sum] simp only [elementaryQuery] simp_rw [testQuery_failure] · simp_rw [localTest_mean] rw [sum_invcard_mul,expect_prod_type] simp only [expect_prod_type,edgeMean,sampleHidden] cases j <;> rflend MinUncut.Outer
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688import Mathlibimport OAI.Computability.MinUncut.PCP.Foldingimport OAI.Computability.MinUncut.Encoding.BinaryLinear
namespace OAI
sectionnamespace MinUncutGames.Reduction.ActualSource
open MinUncutGames.Integration.BinaryLinear
structure Source where «variables» : Nat occurrences : Nat nonempty : 0 < occurrences equation : Fin occurrences → CloneGap.Equation (Fin «variables»)
def Source.sourceList (S : Source) : List (CloneGap.Equation (Fin S.«variables»)) := List.ofFn S.equation
def Source.ofList {n : Nat} (es : List (CloneGap.Equation (Fin n))) (hne : es ≠ []) : Source where «variables» := n occurrences := es.length nonempty := List.length_pos_iff.mpr hne equation := es.get
@[simp] theorem Source.sourceList_ofList {n : Nat} (es : List (CloneGap.Equation (Fin n))) (hne : es ≠ []) : (Source.ofList es hne).sourceList = es := by exact List.ofFn_getElem
@[simp] theorem Source.sourceList_length (S : Source) : S.sourceList.length = S.occurrences := by simp [Source.sourceList]
theorem Source.sourceList_nonempty (S : Source) : S.sourceList ≠ [] := by intro h have hp := S.nonempty have hn := S.sourceList_length rw [h] at hn simp only [List.length_nil] at hn omega
instance sourceIndexNonempty (S : Source) : Nonempty (Fin S.occurrences) := ⟨⟨0, S.nonempty⟩⟩
def Source.satisfied (S : Source) (A : Fin S.«variables» → Bool) (i : Fin S.occurrences) : Bool := CloneGap.satisfied (S.equation i) A
def Source.failure (S : Source) (A : Fin S.«variables» → Bool) : ℚ := Finset.univ.expect (fun i => if S.satisfied A i then (0 : ℚ) else 1)
def Source.DistinctNames (S : Source) : Prop := ∀ i, (S.equation i).first ≠ (S.equation i).second ∧ (S.equation i).first ≠ (S.equation i).third ∧ (S.equation i).second ≠ (S.equation i).third
abbrev Alphabet (s : Nat) := MinUncutGames.Integration.BinaryLinear.Vector sabbrev Ambient (s d : Nat) := Alphabet s × MinUncutGames.Integration.BinaryLinear.Vector d
def alphabetEmbedding (s d : Nat) : Alphabet s →ₗ[F2] Ambient s d := LinearMap.inl F2 (Alphabet s) (MinUncutGames.Integration.BinaryLinear.Vector d)
@[simp] theorem alphabetEmbedding_apply (s d : Nat) (c : Alphabet s) : alphabetEmbedding s d c = (c, 0) := rfl
structure SplitGadget (s d : Nat) where f : Ambient s d → Alphabet s equivariant : ∀ (x : Ambient s d) (c : Alphabet s), f (x + (c, 0)) = f x + c NoiseIndex : Type noiseFintype : Fintype NoiseIndex noiseNonempty : Nonempty NoiseIndex noise : NoiseIndex → Ambient s d
attribute [instance] SplitGadget.noiseFintype SplitGadget.noiseNonempty
def SplitGadget.stabilityError {s d : Nat} (g : SplitGadget s d) : ℚ := Finset.univ.expect (fun xv : Ambient s d × g.NoiseIndex => if g.f (xv.1 + g.noise xv.2) = g.f xv.1 then (0 : ℚ) else 1)
def SplitGadget.kernelError {s d p : Nat} (g : SplitGadget s d) (S : Ambient s d →ₗ[F2] MinUncutGames.Integration.BinaryLinear.Vector p) : ℚ := Finset.univ.expect (fun i => if S (g.noise i) = 0 then (1 : ℚ) else 0)
theorem SplitGadget.stabilityError_nonneg {s d : Nat} (g : SplitGadget s d) : 0 ≤ g.stabilityError := by apply Finset.expect_nonneg intro x _ split <;> norm_num
theorem SplitGadget.stabilityError_le_one {s d : Nat} (g : SplitGadget s d) : g.stabilityError ≤ 1 := by apply Finset.expect_le Finset.univ_nonempty intro x _ split <;> norm_num
end MinUncutGames.Reduction.ActualSource
endsectionnamespace MinUncutGames.Reduction.Incidence
universe u vvariable {Variable : Type u} {Index : Type v}
structure Triple where first : Bool second : Bool third : Bool deriving DecidableEq
def parity (a : Triple) : Bool := (a.first.xor a.second).xor a.third
def matchingSlots (a b : Triple) : Nat := (if a.first = b.first then 1 else 0) + (if a.second = b.second then 1 else 0) + (if a.third = b.third then 1 else 0)
def acceptedSlots (a b : Triple) (rhs : Bool) : Nat := if parity a = rhs then matchingSlots a b else 0
def failedEquation (b : Triple) (rhs : Bool) : Nat := if parity b = rhs then 0 else 1
def bestResponse (b : Triple) (rhs : Bool) : Triple := if parity b = rhs then b else { b with first := !b.first }
theorem local_count_bound (a b : Triple) (rhs : Bool) : acceptedSlots a b rhs + failedEquation b rhs ≤ 3 := by rcases a with ⟨a₁, a₂, a₃⟩ rcases b with ⟨b₁, b₂, b₃⟩ cases a₁ <;> cases a₂ <;> cases a₃ <;> cases b₁ <;> cases b₂ <;> cases b₃ <;> cases rhs <;> decide
theorem best_response_exact (b : Triple) (rhs : Bool) : acceptedSlots (bestResponse b rhs) b rhs + failedEquation b rhs = 3 := by rcases b with ⟨b₁, b₂, b₃⟩ cases b₁ <;> cases b₂ <;> cases b₃ <;> cases rhs <;> decide
structure Equation (Variable : Type u) where first : Variable second : Variable third : Variable rhs : Bool
inductive Slot where | first | second | third deriving DecidableEq
def nameAt (e : Equation Variable) : Slot → Variable | .first => e.first | .second => e.second | .third => e.third
def bitAt (a : Triple) : Slot → Bool | .first => a.first | .second => a.second | .third => a.third
def questionPredicate (e : Equation Variable) (name : Variable) (alice : Triple) (bob : Bool) : Prop := parity alice = e.rhs ∧ ((e.first = name ∧ alice.first = bob) ∨ (e.second = name ∧ alice.second = bob) ∨ (e.third = name ∧ alice.third = bob))
theorem question_predicate_at_slot (e : Equation Variable) (distinct₁₂ : e.first ≠ e.second) (distinct₁₃ : e.first ≠ e.third) (distinct₂₃ : e.second ≠ e.third) (alice : Triple) (bob : Bool) (slot : Slot) : questionPredicate e (nameAt e slot) alice bob ↔ parity alice = e.rhs ∧ bitAt alice slot = bob := by cases slot <;> simp [questionPredicate, nameAt, bitAt, distinct₁₂, distinct₁₃, distinct₂₃, Ne.symm distinct₁₂, Ne.symm distinct₁₃, Ne.symm distinct₂₃]
def bobTriple (g : Variable → Bool) (e : Equation Variable) : Triple := ⟨g e.first, g e.second, g e.third⟩
def acceptedCount (equations : Index → Equation Variable) (g : Variable → Bool) (alice : Index → Triple) : List Index → Nat | [] => 0 | i :: rest => acceptedSlots (alice i) (bobTriple g (equations i)) (equations i).rhs + acceptedCount equations g alice rest
def failureCount (equations : Index → Equation Variable) (g : Variable → Bool) : List Index → Nat | [] => 0 | i :: rest => failedEquation (bobTriple g (equations i)) (equations i).rhs + failureCount equations g rest
theorem total_count_bound (equations : Index → Equation Variable) (g : Variable → Bool) (alice : Index → Triple) (occurrences : List Index) : acceptedCount equations g alice occurrences + failureCount equations g occurrences ≤ 3 * occurrences.length := by induction occurrences with | nil => simp [acceptedCount, failureCount] | cons i rest ih => have h := local_count_bound (alice i) (bobTriple g (equations i)) (equations i).rhs simp only [acceptedCount, failureCount, List.length_cons] omega
def optimalAlice (equations : Index → Equation Variable) (g : Variable → Bool) (i : Index) : Triple := bestResponse (bobTriple g (equations i)) (equations i).rhs
theorem optimal_alice_exact (equations : Index → Equation Variable) (g : Variable → Bool) (occurrences : List Index) : acceptedCount equations g (optimalAlice equations g) occurrences + failureCount equations g occurrences = 3 * occurrences.length := by induction occurrences with | nil => simp [acceptedCount, failureCount] | cons i rest ih => have h := best_response_exact (bobTriple g (equations i)) (equations i).rhs simp only [acceptedCount, failureCount, List.length_cons, optimalAlice] omega
theorem fixed_bob_optimum (equations : Index → Equation Variable) (g : Variable → Bool) (occurrences : List Index) : ∃ alice : Index → Triple, acceptedCount equations g alice occurrences + failureCount equations g occurrences = 3 * occurrences.length ∧ ∀ other : Index → Triple, acceptedCount equations g other occurrences ≤ acceptedCount equations g alice occurrences := by refine ⟨optimalAlice equations g, optimal_alice_exact equations g occurrences, ?_⟩ intro other have h := total_count_bound equations g other occurrences have heq := optimal_alice_exact equations g occurrences omega
theorem soundness_191_over_192 (equations : Index → Equation Variable) (g : Variable → Bool) (alice : Index → Triple) (occurrences : List Index) (source_gap : occurrences.length ≤ 64 * failureCount equations g occurrences) : 64 * acceptedCount equations g alice occurrences ≤ 191 * occurrences.length := by have h := total_count_bound equations g alice occurrences omega
theorem game_soundness_191_over_192 (equations : Index → Equation Variable) (occurrences : List Index) (source_gap : ∀ g : Variable → Bool, occurrences.length ≤ 64 * failureCount equations g occurrences) : ∀ (g : Variable → Bool) (alice : Index → Triple), 64 * acceptedCount equations g alice occurrences ≤ 191 * occurrences.length := by intro g alice exact soundness_191_over_192 equations g alice occurrences (source_gap g)
end MinUncutGames.Reduction.Incidence
endsectionnamespace MinUncutGames.Reduction.SourceIncidence
variable {Name : Type} {Index : Type*}
def toIncidence (e : CloneGap.Equation Name) : Incidence.Equation Name := ⟨e.first, e.second, e.third, e.rhs⟩
theorem failedEquation_eq (e : CloneGap.Equation Name) (g : Name → Bool) : Incidence.failedEquation (Incidence.bobTriple g (toIncidence e)) (toIncidence e).rhs = if CloneGap.satisfied e g then 0 else 1 := by simp only [Incidence.failedEquation, Incidence.bobTriple, toIncidence, Incidence.parity, CloneGap.satisfied] simp
theorem failureCount_eq (equations : Index → CloneGap.Equation Name) (g : Name → Bool) (occurrences : List Index) : Incidence.failureCount (fun i => toIncidence (equations i)) g occurrences = occurrences.countP (fun i => !CloneGap.satisfied (equations i) g) := by induction occurrences with | nil => rfl | cons i rest ih => simp only [Incidence.failureCount, failedEquation_eq, ih, List.countP_cons] cases CloneGap.satisfied (equations i) g <;> simp omega
def occurrenceList (source : List (CloneGap.Equation Name)) := (CloneGap.cloneList source).zipIdx
theorem cloned_occurrence_gap (source : List (CloneGap.Equation Name)) (source_gap : ∀ A : Name → Bool, source.length ≤ 4 * source.countP (fun e => !CloneGap.satisfied e A)) (g : Name × CloneGap.Index → Bool) : (occurrenceList source).length ≤ 64 * Incidence.failureCount (fun i => toIncidence i.1) g (occurrenceList source) := by have hg := CloneGap.clone_gap source source_gap g rw [failureCount_eq] unfold occurrenceList rw [List.length_zipIdx] have hcount : ((CloneGap.cloneList source).zipIdx).countP (fun i => !CloneGap.satisfied i.1 g) = (CloneGap.cloneList source).countP (fun e => !CloneGap.satisfied e g) := by have h := congrArg (fun es => es.countP (fun e => !CloneGap.satisfied e g)) (List.zipIdx_map_fst 0 (CloneGap.cloneList source)) simpa only [List.countP_map, Function.comp_def] using h rw [hcount] exact hg
theorem source_to_incidence_soundness (source : List (CloneGap.Equation Name)) (source_gap : ∀ A : Name → Bool, source.length ≤ 4 * source.countP (fun e => !CloneGap.satisfied e A)) (g : Name × CloneGap.Index → Bool) (alice : CloneGap.Equation (Name × CloneGap.Index) × Nat → Incidence.Triple) : 64 * Incidence.acceptedCount (fun i => toIncidence i.1) g alice (occurrenceList source) ≤ 191 * (occurrenceList source).length := by exact Incidence.soundness_191_over_192 _ g alice _ (cloned_occurrence_gap source source_gap g)
end MinUncutGames.Reduction.SourceIncidence
endsectionnamespace MinUncutGames.Reduction.FiniteSource
open CloneGap
variable {n : ℕ} {α β : Type*}
abbrev Name (s : ActualSource.Source) := Fin s.«variables» × Fin 48
def clonedSource (s : ActualSource.Source) := cloneList s.sourceList
abbrev Occurrence (s : ActualSource.Source) := Fin (clonedSource s).length
def occurrences (s : ActualSource.Source) : List (Occurrence s) := List.finRange (clonedSource s).length
def rawEquation (s : ActualSource.Source) (i : Occurrence s) : Equation (Fin s.«variables» × Nat) := (clonedSource s)[i.val]
def finiteName (s : ActualSource.Source) (v : Fin s.«variables» × Nat) : Name s := (v.1, ⟨v.2 % 48, Nat.mod_lt _ (by decide)⟩)
def mapEquation {α β : Type} (f : α → β) (e : Equation α) : Equation β := ⟨f e.first, f e.second, f e.third, e.rhs⟩
def equation (s : ActualSource.Source) (i : Occurrence s) : Equation (Name s) := mapEquation (finiteName s) (rawEquation s i)
theorem satisfied_map {α β : Type} (f : α → β) (e : Equation α) (g : β → Bool) : satisfied (mapEquation f e) g = satisfied e (g ∘ f) := rfl
theorem mem_cart {xs : List α} {ys : List β} {z : α × β} : z ∈ cart xs ys ↔ z.1 ∈ xs ∧ z.2 ∈ ys := by simp only [cart, List.mem_flatMap, List.mem_map] constructor · rintro ⟨x, hx, y, hy, h⟩ cases h exact ⟨hx, hy⟩ · rintro ⟨hx, hy⟩ exact ⟨z.1, hx, z.2, hy, rfl⟩
theorem distinctTriple_bounds {t : Nat × Nat × Nat} (h : t ∈ distinctTriples) : t.1 < 48 ∧ t.2.1 < 48 ∧ t.2.2 < 48 := by have h := (List.mem_filter.mp h).1 change t ∈ cart indices (cart indices indices) at h rw [mem_cart, mem_cart] at h simpa [indices] using h
theorem distinctTriples_nonempty : 0 < distinctTriples.length := by have hm : (0, 1, 2) ∈ distinctTriples := by simp [distinctTriples, triples, mem_cart, indices, collision] exact List.length_pos_iff_exists_mem.mpr ⟨_, hm⟩
theorem cloned_member_properties {source : List (Equation (Fin n))} {e : Equation (Fin n × Nat)} (h : e ∈ cloneList source) : (e.first.2 < 48 ∧ e.second.2 < 48 ∧ e.third.2 < 48) ∧ (e.first ≠ e.second ∧ e.first ≠ e.third ∧ e.second ≠ e.third) := by obtain ⟨old, _, h⟩ := List.mem_flatMap.mp h obtain ⟨t, ht, rfl⟩ := List.mem_map.mp h have hb := distinctTriple_bounds ht have hc : collision t = false := by simpa using (List.mem_filter.mp ht).2 exact ⟨hb, clone_names_distinct old t hc⟩
theorem raw_properties (s : ActualSource.Source) (i : Occurrence s) : ((rawEquation s i).first.2 < 48 ∧ (rawEquation s i).second.2 < 48 ∧ (rawEquation s i).third.2 < 48) ∧ ((rawEquation s i).first ≠ (rawEquation s i).second ∧ (rawEquation s i).first ≠ (rawEquation s i).third ∧ (rawEquation s i).second ≠ (rawEquation s i).third) := by apply cloned_member_properties exact List.getElem_mem i.isLt
theorem finiteName_injective_on (s : ActualSource.Source) {u v : Fin s.«variables» × Nat} (hu : u.2 < 48) (hv : v.2 < 48) (h : finiteName s u = finiteName s v) : u = v := by have he := congrArg (fun z : Name s => (z.1, z.2.val)) h simpa [finiteName, Nat.mod_eq_of_lt hu, Nat.mod_eq_of_lt hv] using he
theorem names_distinct (s : ActualSource.Source) (i : Occurrence s) : (equation s i).first ≠ (equation s i).second ∧ (equation s i).first ≠ (equation s i).third ∧ (equation s i).second ≠ (equation s i).third := by obtain ⟨⟨h₁, h₂, h₃⟩, ⟨h₁₂, h₁₃, h₂₃⟩⟩ := raw_properties s i exact ⟨fun h => h₁₂ (finiteName_injective_on s h₁ h₂ h), fun h => h₁₃ (finiteName_injective_on s h₁ h₃ h), fun h => h₂₃ (finiteName_injective_on s h₂ h₃ h)⟩
theorem raw_map_occurrences (s : ActualSource.Source) : (occurrences s).map (rawEquation s) = clonedSource s := by simp [occurrences, List.finRange, List.map_ofFn, rawEquation, Function.comp_def]
theorem occurrences_length (s : ActualSource.Source) : (occurrences s).length = (clonedSource s).length := by simp [occurrences]
theorem clonedSource_nonempty (s : ActualSource.Source) : 0 < (clonedSource s).length := by rw [clonedSource, length_cloneList] have hs : 0 < s.sourceList.length := by simpa [ActualSource.Source.sourceList] using s.nonempty exact Nat.mul_pos hs distinctTriples_nonempty
instance (s : ActualSource.Source) : Nonempty (Occurrence s) := ⟨⟨0, clonedSource_nonempty s⟩⟩
theorem indexed_failure_count (s : ActualSource.Source) (g : Name s → Bool) : (occurrences s).countP (fun i => !satisfied (equation s i) g) = (clonedSource s).countP (fun e => !satisfied e (g ∘ finiteName s)) := by have h := congrArg (fun es => es.countP (fun e => !satisfied e (g ∘ finiteName s))) (raw_map_occurrences s) simpa only [List.countP_map, Function.comp_def, equation, satisfied_map] using h
theorem indexed_gap (s : ActualSource.Source) (source_gap : ∀ A : Fin s.«variables» → Bool, s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !satisfied e A)) (g : Name s → Bool) : (occurrences s).length ≤ 64 * (occurrences s).countP (fun i => !satisfied (equation s i) g) := by rw [occurrences_length, indexed_failure_count] exact clone_gap s.sourceList source_gap (g ∘ finiteName s)
theorem indexed_completeness_count (s : ActualSource.Source) (A : Fin s.«variables» → Bool) : (occurrences s).countP (fun i => satisfied (equation s i) (fun z => A z.1)) = s.sourceList.countP (fun e => satisfied e A) * distinctTriples.length := by have h := congrArg (fun es => es.countP (fun e => satisfied e (fun z => A z.1))) (raw_map_occurrences s) simp only [List.countP_map, Function.comp_def] at h change (occurrences s).countP (fun i => satisfied (rawEquation s i) (fun z => A z.1)) = _ rw [h] exact clone_completeness_count s.sourceList A
def incidenceEquation (s : ActualSource.Source) (i : Occurrence s) : Incidence.Equation (Name s) := SourceIncidence.toIncidence (equation s i)
theorem incidence_question_predicate (s : ActualSource.Source) (i : Occurrence s) (alice : Incidence.Triple) (bob : Bool) (slot : Incidence.Slot) : Incidence.questionPredicate (incidenceEquation s i) (Incidence.nameAt (incidenceEquation s i) slot) alice bob ↔ Incidence.parity alice = (incidenceEquation s i).rhs ∧ Incidence.bitAt alice slot = bob := by obtain ⟨h₁₂, h₁₃, h₂₃⟩ := names_distinct s i exact Incidence.question_predicate_at_slot _ h₁₂ h₁₃ h₂₃ alice bob slot
theorem incidence_failure_gap (s : ActualSource.Source) (source_gap : ∀ A : Fin s.«variables» → Bool, s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !satisfied e A)) (g : Name s → Bool) : (occurrences s).length ≤ 64 * Incidence.failureCount (incidenceEquation s) g (occurrences s) := by unfold incidenceEquation rw [SourceIncidence.failureCount_eq] exact indexed_gap s source_gap g
theorem incidence_soundness (s : ActualSource.Source) (source_gap : ∀ A : Fin s.«variables» → Bool, s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !satisfied e A)) (g : Name s → Bool) (alice : Occurrence s → Incidence.Triple) : 64 * Incidence.acceptedCount (incidenceEquation s) g alice (occurrences s) ≤ 191 * (occurrences s).length := Incidence.soundness_191_over_192 _ g alice _ (incidence_failure_gap s source_gap g)
def nameEquiv (s : ActualSource.Source) : Name s ≃ Fin (s.«variables» * 48) := finProdFinEquiv
def cloned (s : ActualSource.Source) : ActualSource.Source where «variables» := s.«variables» * 48 occurrences := (clonedSource s).length nonempty := clonedSource_nonempty s equation i := mapEquation (nameEquiv s) (equation s i)
theorem cloned_length (s : ActualSource.Source) : (cloned s).occurrences = s.occurrences * distinctTriples.length := by change (cloneList s.sourceList).length = _ rw [length_cloneList, ActualSource.Source.sourceList_length]
theorem cloned_distinct (s : ActualSource.Source) : (cloned s).DistinctNames := by intro i obtain ⟨h₁₂, h₁₃, h₂₃⟩ := names_distinct s i exact ⟨fun h => h₁₂ ((nameEquiv s).injective h), fun h => h₁₃ ((nameEquiv s).injective h), fun h => h₂₃ ((nameEquiv s).injective h)⟩
theorem count_ofFn (f : Fin n → α) (p : α → Bool) : (List.ofFn f).countP p = (List.finRange n).countP (fun i => p (f i)) := by have he : (List.finRange n).map f = List.ofFn f := by simp [List.finRange, List.map_ofFn, Function.comp_def] have h := congrArg (fun es => es.countP p) he simpa only [List.countP_map, Function.comp_def] using h.symm
theorem cloned_gap (s : ActualSource.Source) (source_gap : ∀ A : Fin s.«variables» → Bool, s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !satisfied e A)) (A : Fin (cloned s).«variables» → Bool) : (cloned s).sourceList.length ≤ 64 * (cloned s).sourceList.countP (fun e => !satisfied e A) := by change Fin (s.«variables» * 48) → Bool at A have h := indexed_gap s source_gap (A ∘ nameEquiv s) rw [occurrences_length] at h change (List.ofFn (fun i => mapEquation (nameEquiv s) (equation s i))).length ≤ 64 * (List.ofFn (fun i => mapEquation (nameEquiv s) (equation s i))).countP (fun e => !satisfied e A) rw [List.length_ofFn, count_ofFn] exact h
theorem cloned_completeness_count (s : ActualSource.Source) (A : Fin s.«variables» → Bool) : (cloned s).sourceList.countP (fun e => satisfied e (fun z => A ((nameEquiv s).symm z).1)) = s.sourceList.countP (fun e => satisfied e A) * distinctTriples.length := by have h := indexed_completeness_count s A simpa only [ActualSource.Source.sourceList, count_ofFn, cloned, satisfied_map, Function.comp_def, Equiv.symm_apply_apply, occurrences] using h
end MinUncutGames.Reduction.FiniteSource
endsectionnamespace MinUncutGames.Soundness.IncidenceExtraction
abbrev Triple := Fin 3 → Bool
def xorTriple (x : Triple) : Bool := (x 0 ^^ x 1) ^^ x 2
structure Incidence (Occurrence Name : Type) where name : Occurrence → Fin 3 → Name rhs : Occurrence → Bool
def Incidence.accepts {Occurrence Name : Type} (g : Incidence Occurrence Name) (o : Occurrence) (i : Fin 3) (a : Triple) (b : Bool) : Prop := xorTriple a = g.rhs o ∧ a i = b
def Incidence.namedAccepts {Occurrence Name : Type} (g : Incidence Occurrence Name) (o : Occurrence) (n : Name) (a : Triple) (b : Bool) : Prop := ∃ i, g.name o i = n ∧ g.accepts o i a b
theorem Incidence.accepts_implies_namedAccepts {Occurrence Name : Type} (g : Incidence Occurrence Name) (o : Occurrence) (i : Fin 3) (a : Triple) (b : Bool) (h : g.accepts o i a b) : g.namedAccepts o (g.name o i) a b := ⟨i, rfl, h⟩
theorem Incidence.namedAccepts_iff_accepts {Occurrence Name : Type} (g : Incidence Occurrence Name) (distinct : ∀ o i j, g.name o i = g.name o j → i = j) (o : Occurrence) (i : Fin 3) (a : Triple) (b : Bool) : g.namedAccepts o (g.name o i) a b ↔ g.accepts o i a b := by constructor · rintro ⟨j, hname, h⟩ have hji := distinct o j i hname simpa [hji] using h · exact g.accepts_implies_namedAccepts o i a b
structure FullPoint (Position : Type) where homogeneous : Bool coords : Position → Triple
def FullPoint.valid {Position Occurrence Name : Type} (g : Incidence Occurrence Name) (u : Position → Occurrence) (e : FullPoint Position) : Prop := ∀ j, xorTriple (e.coords j) = (g.rhs (u j) && e.homogeneous)
structure PartnerPoint (Position : Type) where homogeneous : Bool single : Position → Bool
def AugmentedAccepts {Position Occurrence Name : Type} (g : Incidence Occurrence Name) (u : Position → Occurrence) (active : Position → Prop) (slot : Position → Fin 3) (eA : FullPoint Position) (eB : PartnerPoint Position) : Prop := eA.valid g u ∧ eA.homogeneous = true ∧ eB.homogeneous = true ∧ ∀ j, active j → eA.coords j (slot j) = eB.single j
def RepeatedAccepts {Position Occurrence Name : Type} (g : Incidence Occurrence Name) (u : Position → Occurrence) (slot : Position → Fin 3) (inside : Position → Prop) (answerA : Position → Triple) (answerB : Position → Bool) : Prop := ∀ j, inside j → g.accepts (u j) (slot j) (answerA j) (answerB j)
theorem augmented_accepts_implies_repeated_accepts {Position Occurrence Name : Type} (g : Incidence Occurrence Name) (u : Position → Occurrence) (active inside : Position → Prop) (slot : Position → Fin 3) (eA : FullPoint Position) (eB : PartnerPoint Position) (hinside : ∀ j, inside j → active j) (haccept : AugmentedAccepts g u active slot eA eB) : RepeatedAccepts g u slot inside eA.coords eB.single := by obtain ⟨hvalid, hone, _, hagree⟩ := haccept intro j hj constructor · have heq := hvalid j simpa [hone] using heq · exact hagree j (hinside j hj)
theorem augmented_accepts_implies_named_repeated_accepts {Position RepeatPosition Occurrence Name : Type} (g : Incidence Occurrence Name) (u : Position → Occurrence) (active : Position → Prop) (slot : Position → Fin 3) (embed : RepeatPosition → Position) (eA : FullPoint Position) (eB : PartnerPoint Position) (hinside : ∀ r, active (embed r)) (haccept : AugmentedAccepts g u active slot eA eB) : ∀ r, g.namedAccepts (u (embed r)) (g.name (u (embed r)) (slot (embed r))) (eA.coords (embed r)) (eB.single (embed r)) := by intro r apply g.accepts_implies_namedAccepts obtain ⟨hvalid, hone, _, hagree⟩ := haccept constructor · have heq := hvalid (embed r) simpa [hone] using heq · exact hagree (embed r) (hinside r)
structure Game (QA QB A B : Type) where accepts : QA → QB → A → B → Prop
structure Strategies (QA QB A B : Type) where first : QA → A second : QB → B
def Strategies.wins {QA QB A B : Type} (s : Strategies QA QB A B) (g : Game QA QB A B) (qa : QA) (qb : QB) : Prop := g.accepts qa qb (s.first qa) (s.second qb)
structure LocalSimulation {InnerQA InnerQB InnerA InnerB OuterQA OuterQB OuterA OuterB : Type} (inner : Game InnerQA InnerQB InnerA InnerB) (outer : Game OuterQA OuterQB OuterA OuterB) where questionA : InnerQA → OuterQA questionB : InnerQB → OuterQB answerA : InnerQA → OuterA → InnerA answerB : InnerQB → OuterB → InnerB sound : ∀ qa qb a b, outer.accepts (questionA qa) (questionB qb) a b → inner.accepts qa qb (answerA qa a) (answerB qb b)
def LocalSimulation.induced {InnerQA InnerQB InnerA InnerB OuterQA OuterQB OuterA OuterB : Type} {inner : Game InnerQA InnerQB InnerA InnerB} {outer : Game OuterQA OuterQB OuterA OuterB} (r : LocalSimulation inner outer) (s : Strategies OuterQA OuterQB OuterA OuterB) : Strategies InnerQA InnerQB InnerA InnerB where first qa := r.answerA qa (s.first (r.questionA qa)) second qb := r.answerB qb (s.second (r.questionB qb))
theorem LocalSimulation.induced_wins {InnerQA InnerQB InnerA InnerB OuterQA OuterQB OuterA OuterB : Type} {inner : Game InnerQA InnerQB InnerA InnerB} {outer : Game OuterQA OuterQB OuterA OuterB} (r : LocalSimulation inner outer) (s : Strategies OuterQA OuterQB OuterA OuterB) (qa : InnerQA) (qb : InnerQB) (hwins : s.wins outer (r.questionA qa) (r.questionB qb)) : (r.induced s).wins inner qa qb := r.sound qa qb (s.first (r.questionA qa)) (s.second (r.questionB qb)) hwins
theorem LocalSimulation.seeded_induced_wins {InnerQA InnerQB InnerA InnerB OuterQA OuterQB OuterA OuterB Seed : Type} {inner : Game InnerQA InnerQB InnerA InnerB} {outer : Game OuterQA OuterQB OuterA OuterB} (r : LocalSimulation inner outer) (strategy : Seed → Strategies OuterQA OuterQB OuterA OuterB) (seed : Seed) (qa : InnerQA) (qb : InnerQB) (hwins : (strategy seed).wins outer (r.questionA qa) (r.questionB qb)) : (r.induced (strategy seed)).wins inner qa qb := r.induced_wins (strategy seed) qa qb hwins
end MinUncutGames.Soundness.IncidenceExtraction
end
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import Mathlibimport OAI.Computability.MinUncut.Games.TripleKernel
namespace OAI
sectionnoncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Compositionopen BinaryFourier OuterSmoothnessattribute [local instance] Classical.propDecidable BinaryFourier.dualFintype
abbrev TripleIndex (J : Type*) := Option (Option (Option J))
def tripleTupleEquiv {J A : Type*} : (TripleIndex J → A) ≃ ((J → A) × (A × A × A)) where toFun L := (fun j => L (some (some (some j))), L none,L (some none),L (some (some none))) invFun z | none => z.2.1 | some none => z.2.2.1 | some (some none) => z.2.2.2 | some (some (some j)) => z.1 j left_inv L := by funext j; cases j with | none => rfl | some j => cases j with | none => rfl | some j => cases j <;> rfl right_inv _ := rfl
lemma TripleIndex.card (J : Type*) [Fintype J] : Fintype.card (TripleIndex J)=Fintype.card J+3 := by simp [TripleIndex]
variable {J V W : Type*} [Fintype J] [DecidableEq J] [AddCommGroup V] [Module F₂ V] [Fintype V] [AddCommGroup W] [Module F₂ W] [Fintype W]
def adaptiveKernel (f : (J → V) → V → ℝ) (u : ℝ) (L : TripleIndex J → V) : ℝ := tripleKernel (remainder (f (tripleTupleEquiv L).1) u) (tripleTupleEquiv L).2
omit [Fintype J] [DecidableEq J] inlemma adaptiveKernel_abs (f : (J → V) → V → ℝ) {M u : ℝ} (hM : 0≤M) (hu : 0<u) (hf : ∀ D z, |f D z|≤M) (L : TripleIndex J → V) : |adaptiveKernel f u L|≤(M+M^2/u)^4 := tripleKernel_abs _ (by positivity) (remainder_abs_bound _ hM hu (hf _)) _
lemma adaptiveKernel_uniform (f : (J → V) → V → ℝ) {M u : ℝ} (hM : 0≤M) (hu : 0<u) (hf : ∀ D z, |f D z|≤M) : (𝔼 L : TripleIndex J → V, adaptiveKernel f u L)≤u^2*M^2 := by have he : (𝔼 L : TripleIndex J → V, adaptiveKernel f u L) = 𝔼 z : (J → V) × (V × V × V), tripleKernel (remainder (f z.1) u) z.2 := Fintype.expect_equiv tripleTupleEquiv _ _ (fun _ => rfl) rw [he,expect_pair] simp_rw [tripleKernel_mean] exact (Finset.expect_le_expect (fun D _ => remainder_fourth_bound (f D) hM hu (hf D))).trans_eq (Fintype.expect_const _)
omit [Fintype J] [DecidableEq J] [Fintype W] inlemma adaptiveKernel_pullback (π : W →ₗ[F₂] V) (f : (J → V) → V → ℝ) (u : ℝ) (L : TripleIndex J → W) : adaptiveKernel f u (fun j => π (L j)) = tripleKernel (fun z => remainder (f (fun j => π ((tripleTupleEquiv L).1 j))) u (π z)) (tripleTupleEquiv L).2 := by simp only [adaptiveKernel,tripleKernel,tripleTupleEquiv,Equiv.coe_fn_mk,map_add]
lemma adaptiveKernel_pullback_mean (π : W →ₗ[F₂] V) (f : (J → V) → V → ℝ) (u : ℝ) : (𝔼 L : TripleIndex J → W, adaptiveKernel f u (fun j => π (L j))) = 𝔼 D : J → W, ∑ β : Module.Dual F₂ W, coefficient (fun z => remainder (f (fun j => π (D j))) u (π z)) β ^4 := by simp_rw [adaptiveKernel_pullback] have he := Fintype.expect_equiv (tripleTupleEquiv (J := J) (A := W)) (fun L => tripleKernel (fun z => remainder (f (fun j => π ((tripleTupleEquiv L).1 j))) u (π z)) (tripleTupleEquiv L).2) (fun z => tripleKernel (fun w => remainder (f (fun j => π (z.1 j))) u (π w)) z.2) (fun _ => rfl) rw [he,expect_pair] simp_rw [tripleKernel_mean]
end MinUncut.Composition
endend
end OAI12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import Mathlibimport OAI.Computability.MinUncut.Estimates.F2
namespace OAI
sectionnoncomputable sectionnamespace MinUncut.Inneropen BinaryFouriervariable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A]
def labelFrequency (a : A) : Module.Dual F₂ (Forms A) where toFun b := b a map_add' _ _ := rfl map_smul' _ _ := rfl
@[simp] lemma labelFrequency_apply (a : A) (b : Forms A) : labelFrequency a b = b a := rfl@[simp] lemma labelFrequency_odd (a : A) : labelFrequency a (AffineMap.const F₂ A 1) = 1 := rfl
def basedForm (a₀ : A) : Module.Dual F₂ V →ₗ[F₂] Forms A where toFun l := l.toAffineMap.comp (AffineEquiv.vaddConst F₂ a₀).symm.toAffineMap map_add' l k := by ext a; rfl map_smul' t l := by ext a; rfl
@[simp] lemma basedForm_apply (a₀ a : A) (l : Module.Dual F₂ V) : basedForm a₀ l a = l (a -ᵥ a₀) := rfl
lemma form_decomposition (a₀ : A) (b : Forms A) : b = basedForm a₀ b.linear + b a₀ • AffineMap.const F₂ A 1 := by ext a have h := b.map_vadd a₀ (a -ᵥ a₀) simpa only [vsub_vadd, vadd_eq_add, AffineMap.coe_add, AffineMap.coe_smul, Pi.add_apply, Pi.smul_apply, AffineMap.const_apply, smul_eq_mul, mul_one, basedForm_apply] using h
lemma labelFrequency_injective : Function.Injective (labelFrequency (A := A)) := by intro a a' h have hlin : (Module.Dual.eval F₂ V) (a -ᵥ a') = 0 := by ext l have hh := congrArg (fun α : Module.Dual F₂ (Forms A) => α (basedForm a' l)) h simpa using hh have hz : a -ᵥ a' = 0 := (Module.eval_apply_eq_zero_iff F₂ _).mp hlin exact vsub_eq_zero_iff_eq.mp hz
variable [Fintype A]
lemma oddFrequency_exists_label (α : Module.Dual F₂ (Forms A)) (hα : α (AffineMap.const F₂ A 1) = 1) : ∃ a : A, labelFrequency a = α := by let a₀ : A := Classical.choice (inferInstance : Nonempty A) let : Fintype V := Fintype.ofEquiv A (AffineEquiv.vaddConst F₂ a₀).toEquiv.symm obtain ⟨v,hv⟩ := (Module.bijective_dual_eval F₂ V).2 (α.comp (basedForm a₀)) refine ⟨v +ᵥ a₀, ?_⟩ apply LinearMap.ext intro b have hb : α b = b.linear v + b a₀ := by conv_lhs => rw [form_decomposition a₀ b] rw [map_add, map_smul, hα] have hh := congrArg (fun β : Module.Dual F₂ (Module.Dual F₂ V) => β b.linear) hv change b.linear v = α (basedForm a₀ b.linear) at hh rw [← hh] simp simpa only [labelFrequency_apply, AffineMap.map_vadd, vadd_eq_add] using hb.symm
def oddFrequencyEquiv : A ≃ {α : Module.Dual F₂ (Forms A) // α (AffineMap.const F₂ A 1) = 1} := Equiv.ofBijective (fun a => ⟨labelFrequency a, labelFrequency_odd a⟩) ⟨fun _ _ h => labelFrequency_injective (congrArg Subtype.val h), fun α => by obtain ⟨a,ha⟩ := oddFrequency_exists_label α.val α.property exact ⟨a, Subtype.ext ha⟩⟩
variable {V' A' : Type*} [AddCommGroup V'] [Module F₂ V'] [AddTorsor V' A']
def formPullback (π : A →ᵃ[F₂] A') : Forms A' →ₗ[F₂] Forms A where toFun b := b.comp π map_add' _ _ := by ext a; rfl map_smul' _ _ := by ext a; rfl
omit [Fintype A] in@[simp] lemma formPullback_one (π : A →ᵃ[F₂] A') : formPullback π (AffineMap.const F₂ A' 1) = AffineMap.const F₂ A 1 := by ext a; rfl
omit [Fintype A] in@[simp] lemma labelFrequency_pullback (π : A →ᵃ[F₂] A') (a : A) : (labelFrequency a).comp (formPullback π) = labelFrequency (π a) := rflend MinUncut.Inner
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684import Mathlibimport OAI.Computability.MinUncut.Games.OuterQuestions
namespace OAI
namespace MinUncutGames.Foundations.CorrelatedSampling
def firstAccepted {σ : Type*} (accept : σ → Bool) : List σ → Option σ | [] => none | proposal :: rest => if accept proposal then some proposal else firstAccepted accept rest
theorem first_union_common {σ : Type*} (left right : σ → Bool) (proposals : List σ) (proposal : σ) (hfirst : firstAccepted (fun s => left s || right s) proposals = some proposal) (hleft : left proposal = true) (hright : right proposal = true) : firstAccepted left proposals = some proposal ∧ firstAccepted right proposals = some proposal := by induction proposals with | nil => simp [firstAccepted] at hfirst | cons head tail ih => by_cases hl : left head = true · have heq : head = proposal := by simpa [firstAccepted, hl] using hfirst subst head simp [firstAccepted, hleft, hright] · by_cases hr : right head = true · have heq : head = proposal := by simpa [firstAccepted, hl, hr] using hfirst subst head exact False.elim (hl hleft) · have htail : firstAccepted (fun s => left s || right s) tail = some proposal := by simpa [firstAccepted, hl, hr] using hfirst simpa [firstAccepted, hl, hr] using ih htail
def thresholdSample {α : Type*} (mass : α → Nat) (proposals : List (α × Nat)) : Option α := (firstAccepted (fun s => decide (s.2 < mass s.1)) proposals).map Prod.fst
theorem thresholdSample_agreement {α : Type*} (left right : α → Nat) (proposals : List (α × Nat)) (a : α) (height : Nat) (hfirst : firstAccepted (fun s => decide (s.2 < left s.1) || decide (s.2 < right s.1)) proposals = some (a, height)) (hcommon : height < min (left a) (right a)) : thresholdSample left proposals = some a ∧ thresholdSample right proposals = some a := by have h := first_union_common (fun s : α × Nat => decide (s.2 < left s.1)) (fun s : α × Nat => decide (s.2 < right s.1)) proposals (a, height) hfirst (by simpa using (lt_min_iff.mp hcommon).1) (by simpa using (lt_min_iff.mp hcommon).2) simp [thresholdSample, h.1, h.2]
noncomputable section
variable {α : Type*} [Fintype α]
def totalVariation (p q : α → ℝ) : ℝ := (∑ a, |p a - q a|) / 2
def overlapMass (p q : α → ℝ) : ℝ := ∑ a, min (p a) (q a)
def unionMass (p q : α → ℝ) : ℝ := ∑ a, max (p a) (q a)
theorem totalVariation_nonneg (p q : α → ℝ) : 0 ≤ totalVariation p q := by unfold totalVariation exact div_nonneg (Finset.sum_nonneg (fun _ _ => abs_nonneg _)) (by norm_num)
theorem overlapMass_nonneg (p q : α → ℝ) (hp : ∀ a, 0 ≤ p a) (hq : ∀ a, 0 ≤ q a) : 0 ≤ overlapMass p q := by exact Finset.sum_nonneg (fun a _ => le_min (hp a) (hq a))
private theorem min_abs_identity (x y : ℝ) : 2 * min x y + |x - y| = x + y := by rcases le_total x y with h | h · rw [min_eq_left h, abs_of_nonpos (sub_nonpos.mpr h)] ring · rw [min_eq_right h, abs_of_nonneg (sub_nonneg.mpr h)] ring
private theorem max_abs_identity (x y : ℝ) : 2 * max x y - |x - y| = x + y := by rcases le_total x y with h | h · rw [max_eq_right h, abs_of_nonpos (sub_nonpos.mpr h)] ring · rw [max_eq_left h, abs_of_nonneg (sub_nonneg.mpr h)] ring
theorem overlapMass_eq (p q : α → ℝ) (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) : overlapMass p q = 1 - totalVariation p q := by have h := Finset.sum_congr (s₁ := Finset.univ) (s₂ := Finset.univ) rfl (fun a _ => min_abs_identity (p a) (q a)) simp only [Finset.sum_add_distrib, ← Finset.mul_sum, hp, hq] at h unfold overlapMass totalVariation linarith
theorem unionMass_eq (p q : α → ℝ) (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) : unionMass p q = 1 + totalVariation p q := by have h := Finset.sum_congr (s₁ := Finset.univ) (s₂ := Finset.univ) rfl (fun a _ => max_abs_identity (p a) (q a)) simp only [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, hp, hq] at h unfold unionMass totalVariation linarith
theorem totalVariation_le_one (p q : α → ℝ) (hp : ∀ a, 0 ≤ p a) (hq : ∀ a, 0 ≤ q a) (hpsum : ∑ a, p a = 1) (hqsum : ∑ a, q a = 1) : totalVariation p q ≤ 1 := by have h := overlapMass_nonneg p q hp hq rw [overlapMass_eq p q hpsum hqsum] at h linarith
theorem overlap_union_ratio (p q : α → ℝ) (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) : overlapMass p q / unionMass p q = (1 - totalVariation p q) / (1 + totalVariation p q) := by rw [overlapMass_eq p q hp hq, unionMass_eq p q hp hq]
theorem overlap_union_ratio_lower_bound (p q : α → ℝ) (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) : 1 - 2 * totalVariation p q ≤ overlapMass p q / unionMass p q := by rw [overlap_union_ratio p q hp hq] have htv := totalVariation_nonneg p q have hden : 0 < 1 + totalVariation p q := by linarith apply (le_div_iff₀ hden).2 nlinarith [sq_nonneg (totalVariation p q)]
theorem first_union_disagreement_upper_bound (p q : α → ℝ) (hp : ∑ a, p a = 1) (hq : ∑ a, q a = 1) : 1 - overlapMass p q / unionMass p q ≤ 2 * totalVariation p q := by linarith [overlap_union_ratio_lower_bound p q hp hq]
variable {σ : Type*} [Fintype σ]
def eventMass (w : σ → ℝ) (event : σ → Bool) : ℝ := ∑ s, if event s then w s else 0
theorem eventMass_nonneg (w : σ → ℝ) (event : σ → Bool) (hw : ∀ s, 0 ≤ w s) : 0 ≤ eventMass w event := by apply Finset.sum_nonneg intro s _ split <;> simp_all
theorem eventMass_complement (w : σ → ℝ) (event : σ → Bool) (hw : ∑ s, w s = 1) : eventMass w event + eventMass w (fun s => !(event s)) = 1 := by unfold eventMass rw [← Finset.sum_add_distrib] calc ∑ s, ((if event s then w s else 0) + (if !event s then w s else 0)) = ∑ s, w s := by apply Finset.sum_congr rfl intro s _ cases event s <;> simp _ = 1 := hw
def geometricMass (r : ℝ) : Nat → ℝ | 0 => 0 | n + 1 => 1 + r * geometricMass r n
theorem geometricMass_nonneg (r : ℝ) (hr : 0 ≤ r) (n : Nat) : 0 ≤ geometricMass r n := by induction n with | zero => simp [geometricMass] | succ n ih => exact add_nonneg (by norm_num) (mul_nonneg hr ih)
theorem geometricMass_identity (r : ℝ) (n : Nat) : (1 - r) * geometricMass r n = 1 - r ^ n := by induction n with | zero => simp [geometricMass] | succ n ih => simp only [geometricMass, pow_succ] calc (1 - r) * (1 + r * geometricMass r n) = (1 - r) + r * ((1 - r) * geometricMass r n) := by ring _ = 1 - r ^ n * r := by rw [ih]; ring
def firstHitWeight (w : σ → ℝ) (accept : σ → Bool) : Nat → Option σ → ℝ | 0, none => 1 | 0, some _ => 0 | n + 1, none => eventMass w (fun s => !(accept s)) * firstHitWeight w accept n none | n + 1, some s => (if accept s then w s else 0) + eventMass w (fun s => !(accept s)) * firstHitWeight w accept n (some s)
theorem firstHitWeight_nonneg (w : σ → ℝ) (accept : σ → Bool) (hw : ∀ s, 0 ≤ w s) (n : Nat) (output : Option σ) : 0 ≤ firstHitWeight w accept n output := by induction n generalizing output with | zero => cases output <;> simp [firstHitWeight] | succ n ih => have hr := eventMass_nonneg w (fun s => !(accept s)) hw cases output with | none => exact mul_nonneg hr (ih none) | some s => apply add_nonneg · split <;> simp_all · exact mul_nonneg hr (ih (some s))
theorem firstHitWeight_none (w : σ → ℝ) (accept : σ → Bool) (n : Nat) : firstHitWeight w accept n none = eventMass w (fun s => !(accept s)) ^ n := by induction n with | zero => simp [firstHitWeight] | succ n ih => simp [firstHitWeight, ih, pow_succ, mul_comm]
theorem firstHitWeight_some (w : σ → ℝ) (accept : σ → Bool) (n : Nat) (s : σ) : firstHitWeight w accept n (some s) = (if accept s then w s else 0) * geometricMass (eventMass w (fun s => !(accept s))) n := by induction n with | zero => simp [firstHitWeight, geometricMass] | succ n ih => rw [firstHitWeight, geometricMass, ih] ring
theorem firstHitWeight_normalized (w : σ → ℝ) (accept : σ → Bool) (hw : ∑ s, w s = 1) (n : Nat) : ∑ output, firstHitWeight w accept n output = 1 := by rw [Fintype.sum_option, firstHitWeight_none] simp_rw [firstHitWeight_some] rw [← Finset.sum_mul] change eventMass w (fun s => !(accept s)) ^ n + eventMass w accept * geometricMass (eventMass w (fun s => !(accept s))) n = 1 have hc := eventMass_complement w accept hw have hg := geometricMass_identity (eventMass w (fun s => !(accept s))) n have ha : eventMass w accept = 1 - eventMass w (fun s => !(accept s)) := by linarith rw [ha, hg] ring
def goodFirstMass (w : σ → ℝ) (accept good : σ → Bool) (n : Nat) : ℝ := ∑ s, if good s then firstHitWeight w accept n (some s) else 0
theorem goodFirstMass_eq (w : σ → ℝ) (accept good : σ → Bool) (n : Nat) : goodFirstMass w accept good n = eventMass w (fun s => accept s && good s) * geometricMass (eventMass w (fun s => !(accept s))) n := by unfold goodFirstMass eventMass rw [Finset.sum_mul] apply Finset.sum_congr rfl intro s _ rw [firstHitWeight_some] cases ha : accept s <;> cases hg : good s <;> simp [ha, hg, eventMass]
theorem goodFirstMass_exact (w : σ → ℝ) (accept good : σ → Bool) (hw : ∑ s, w s = 1) (ha : eventMass w accept ≠ 0) (n : Nat) : goodFirstMass w accept good n = eventMass w (fun s => accept s && good s) / eventMass w accept * (1 - eventMass w (fun s => !(accept s)) ^ n) := by rw [goodFirstMass_eq] have hc := eventMass_complement w accept hw have hg := geometricMass_identity (eventMass w (fun s => !(accept s))) n have hgeom : eventMass w accept * geometricMass (eventMass w (fun s => !(accept s))) n = 1 - eventMass w (fun s => !(accept s)) ^ n := by have heq : eventMass w accept = 1 - eventMass w (fun s => !(accept s)) := by linarith rw [heq, hg] rw [← hgeom] field_simp
theorem commonMass_le_acceptMass (w : σ → ℝ) (accept good : σ → Bool) (hw : ∀ s, 0 ≤ w s) : eventMass w (fun s => accept s && good s) ≤ eventMass w accept := by apply Finset.sum_le_sum intro s _ cases ha : accept s <;> cases hg : good s <;> simp [ha, hg, hw s]
theorem goodFirstMass_lower_bound (w : σ → ℝ) (accept good : σ → Bool) (hw : ∀ s, 0 ≤ w s) (hw_sum : ∑ s, w s = 1) (ha : 0 < eventMass w accept) (n : Nat) : eventMass w (fun s => accept s && good s) / eventMass w accept - eventMass w (fun s => !(accept s)) ^ n ≤ goodFirstMass w accept good n := by rw [goodFirstMass_exact w accept good hw_sum (ne_of_gt ha) n] have hratio : eventMass w (fun s => accept s && good s) / eventMass w accept ≤ 1 := by apply (div_le_one ha).2 exact commonMass_le_acceptMass w accept good hw have htail : 0 ≤ eventMass w (fun s => !(accept s)) ^ n := pow_nonneg (eventMass_nonneg w (fun s => !(accept s)) hw) n nlinarith
def traceAverage (w : σ → ℝ) : Nat → (List σ → ℝ) → ℝ | 0, observable => observable [] | n + 1, observable => ∑ s, w s * traceAverage w n (fun tail => observable (s :: tail))
theorem traceAverage_const (w : σ → ℝ) (hw : ∑ s, w s = 1) (n : Nat) (c : ℝ) : traceAverage w n (fun _ => c) = c := by induction n with | zero => rfl | succ n ih => simp [traceAverage, ih, ← Finset.sum_mul, hw]
theorem traceAverage_mono (w : σ → ℝ) (hw : ∀ s, 0 ≤ w s) (n : Nat) (f g : List σ → ℝ) (hfg : ∀ xs, f xs ≤ g xs) : traceAverage w n f ≤ traceAverage w n g := by induction n generalizing f g with | zero => exact hfg [] | succ n ih => apply Finset.sum_le_sum intro s _ exact mul_le_mul_of_nonneg_left (ih (fun tail => f (s :: tail)) (fun tail => g (s :: tail)) (fun tail => hfg (s :: tail))) (hw s)
theorem traceAverage_sum {ι : Type*} [Fintype ι] (w : σ → ℝ) (n : Nat) (f : ι → List σ → ℝ) : traceAverage w n (fun xs => ∑ i, f i xs) = ∑ i, traceAverage w n (f i) := by induction n generalizing f with | zero => rfl | succ n ih => simp only [traceAverage] simp_rw [ih, Finset.mul_sum] exact Finset.sum_comm
variable [DecidableEq σ]
theorem firstAccepted_law (w : σ → ℝ) (accept : σ → Bool) (hw : ∑ s, w s = 1) (n : Nat) (output : Option σ) : traceAverage w n (fun proposals => if firstAccepted accept proposals = output then 1 else 0) = firstHitWeight w accept n output := by classical induction n generalizing output with | zero => cases output <;> simp [traceAverage, firstAccepted, firstHitWeight] | succ n ih => have hstep : traceAverage w (n + 1) (fun proposals => if firstAccepted accept proposals = output then 1 else 0) = ∑ s, w s * (if accept s then (if some s = output then 1 else 0) else firstHitWeight w accept n output) := by unfold traceAverage apply Finset.sum_congr rfl intro s _ congr 1 by_cases hs : accept s = true · simp [firstAccepted, hs, traceAverage_const w hw] · simpa [firstAccepted, hs] using ih output rw [hstep] cases output with | none => simp only [Option.some_ne_none, ite_false, firstHitWeight] rw [eventMass, Finset.sum_mul] apply Finset.sum_congr rfl intro s _ cases accept s <;> simp | some t => simp only [Option.some.injEq, firstHitWeight] calc ∑ s, w s * (if accept s then (if s = t then 1 else 0) else firstHitWeight w accept n (some t)) = ∑ s, ((if s = t then (if accept s then w s else 0) else 0) + (if !(accept s) then w s else 0) * firstHitWeight w accept n (some t)) := by apply Finset.sum_congr rfl intro s _ by_cases he : s = t · subst s by_cases hs : accept t = true <;> simp [hs] · by_cases hs : accept s = true <;> simp [hs, he] _ = (if accept t then w t else 0) + eventMass w (fun s => !(accept s)) * firstHitWeight w accept n (some t) := by rw [Finset.sum_add_distrib, ← Finset.sum_mul] simp [eventMass]
def goodFirstIndicator (accept good : σ → Bool) (proposals : List σ) : ℝ := match firstAccepted accept proposals with | none => 0 | some s => if good s then 1 else 0
theorem goodFirstIndicator_expansion (accept good : σ → Bool) (proposals : List σ) : goodFirstIndicator accept good proposals = ∑ s, if good s then (if firstAccepted accept proposals = some s then 1 else 0) else 0 := by classical cases h : firstAccepted accept proposals with | none => simp [goodFirstIndicator, h] | some t => simp only [goodFirstIndicator, h, Option.some.injEq] calc (if good t then (1 : ℝ) else 0) = ∑ s, if t = s then (if good s then (1 : ℝ) else 0) else 0 := by simp _ = ∑ s, if good s then (if t = s then (1 : ℝ) else 0) else 0 := by apply Finset.sum_congr rfl intro s _ by_cases hg : good s = true <;> by_cases ht : t = s <;> simp [hg, ht]
theorem goodFirstIndicator_law (w : σ → ℝ) (accept good : σ → Bool) (hw : ∑ s, w s = 1) (n : Nat) : traceAverage w n (goodFirstIndicator accept good) = goodFirstMass w accept good n := by classical change traceAverage w n (fun xs => goodFirstIndicator accept good xs) = _ simp_rw [goodFirstIndicator_expansion] rw [traceAverage_sum] unfold goodFirstMass apply Finset.sum_congr rfl intro s _ by_cases hg : good s = true · simpa [hg] using firstAccepted_law w accept hw n (some s) · simp [hg, traceAverage_const w hw]
structure ThresholdInterval where lo : ℝ hi : ℝ valid : lo ≤ hi
def splitPoint (I : ThresholdInterval) (t : ℝ) : ℝ := max I.lo (min t I.hi)
def splitLeft (I : ThresholdInterval) (t : ℝ) : ThresholdInterval := ⟨I.lo, splitPoint I t, le_max_left _ _⟩
def splitRight (I : ThresholdInterval) (t : ℝ) : ThresholdInterval := ⟨splitPoint I t, I.hi, max_le I.valid (min_le_right _ _)⟩
def cutAt (r : ℝ) (I : ThresholdInterval) : Prop := I.hi ≤ r ∨ r ≤ I.lo
def intervalCDF (r : ℝ) (I : ThresholdInterval) : ℝ := min r I.hi - min r I.lo
theorem split_cdf (I : ThresholdInterval) (t r : ℝ) : intervalCDF r (splitLeft I t) + intervalCDF r (splitRight I t) = intervalCDF r I := by unfold intervalCDF splitLeft splitRight ring
theorem accepted_interval_mass (I : ThresholdInterval) (r : ℝ) (hc : cutAt r I) : (if I.lo < r then I.hi - I.lo else 0) = intervalCDF r I := by by_cases hl : I.lo < r · have hu : I.hi ≤ r := hc.resolve_right (not_le_of_gt hl) simp [hl, intervalCDF, min_eq_right hu, min_eq_right (le_of_lt hl)] · have hr : r ≤ I.lo := le_of_not_gt hl simp [hl, intervalCDF, min_eq_left hr, min_eq_left (hr.trans I.valid)]
theorem splitLeft_cut (I : ThresholdInterval) (t : ℝ) : cutAt t (splitLeft I t) := by by_cases h : I.lo ≤ t · exact Or.inl (max_le h (min_le_left _ _)) · exact Or.inr (le_of_lt (lt_of_not_ge h))
theorem splitRight_cut (I : ThresholdInterval) (t : ℝ) : cutAt t (splitRight I t) := by by_cases h : t ≤ I.hi · right change t ≤ max I.lo (min t I.hi) rw [min_eq_left h] exact le_max_right _ _ · exact Or.inl (le_of_lt (lt_of_not_ge h))
theorem splitLeft_preserves_cut (I : ThresholdInterval) (t r : ℝ) (h : cutAt r I) : cutAt r (splitLeft I t) := by rcases h with h | h · exact Or.inl ((max_le I.valid (min_le_right _ _)).trans h) · exact Or.inr h
theorem splitRight_preserves_cut (I : ThresholdInterval) (t r : ℝ) (h : cutAt r I) : cutAt r (splitRight I t) := by rcases h with h | h · exact Or.inl h · exact Or.inr (h.trans (le_max_left _ _))
def splitAll (t : ℝ) : List ThresholdInterval → List ThresholdInterval | [] => [] | I :: rest => splitLeft I t :: splitRight I t :: splitAll t rest
def unitThresholdInterval : ThresholdInterval := ⟨0, 1, by norm_num⟩
def thresholdPartition : List ℝ → List ThresholdInterval | [] => [unitThresholdInterval] | t :: rest => splitAll t (thresholdPartition rest)
def sumOnIntervals (f : ThresholdInterval → ℝ) : List ThresholdInterval → ℝ | [] => 0 | I :: rest => f I + sumOnIntervals f rest
theorem sumOn_splitAll (f : ThresholdInterval → ℝ) (t : ℝ) (hf : ∀ I, f (splitLeft I t) + f (splitRight I t) = f I) (intervals : List ThresholdInterval) : sumOnIntervals f (splitAll t intervals) = sumOnIntervals f intervals := by induction intervals with | nil => rfl | cons I rest ih => simp only [splitAll, sumOnIntervals, ih] rw [← add_assoc, hf]
theorem partition_sum (f : ThresholdInterval → ℝ) (hf : ∀ t I, f (splitLeft I t) + f (splitRight I t) = f I) (thresholds : List ℝ) : sumOnIntervals f (thresholdPartition thresholds) = f unitThresholdInterval := by induction thresholds with | nil => simp [thresholdPartition, sumOnIntervals] | cons t rest ih => rw [thresholdPartition, sumOn_splitAll f t (hf t), ih]
theorem partition_total_mass (thresholds : List ℝ) : sumOnIntervals (fun I => I.hi - I.lo) (thresholdPartition thresholds) = 1 := by have h := partition_sum (fun I => I.hi - I.lo) (fun t I => by simp only [splitLeft, splitRight]; ring) thresholds simpa [unitThresholdInterval] using h
theorem partition_cdf (thresholds : List ℝ) (r : ℝ) (h0 : 0 ≤ r) (h1 : r ≤ 1) : sumOnIntervals (intervalCDF r) (thresholdPartition thresholds) = r := by have h := partition_sum (intervalCDF r) (fun t I => split_cdf I t r) thresholds simpa [intervalCDF, unitThresholdInterval, min_eq_left h1, min_eq_right h0] using h
theorem splitAll_new_cuts (intervals : List ThresholdInterval) (t : ℝ) : ∀ I ∈ splitAll t intervals, cutAt t I := by induction intervals with | nil => intro I h; simp [splitAll] at h | cons J rest ih => intro I h rcases List.mem_cons.mp h with h | h · subst I; exact splitLeft_cut J t · rcases List.mem_cons.mp h with h | h · subst I; exact splitRight_cut J t · exact ih I h
theorem splitAll_preserves_cuts (intervals : List ThresholdInterval) (t r : ℝ) : (∀ I ∈ intervals, cutAt r I) → ∀ I ∈ splitAll t intervals, cutAt r I := by induction intervals with | nil => intro _ I h; simp [splitAll] at h | cons J rest ih => intro hc I h have hJ : cutAt r J := hc J (by simp) have hrest : ∀ K ∈ rest, cutAt r K := fun K hK => hc K (by simp [hK]) rcases List.mem_cons.mp h with h | h · subst I; exact splitLeft_preserves_cut J t r hJ · rcases List.mem_cons.mp h with h | h · subst I; exact splitRight_preserves_cut J t r hJ · exact ih hrest I h
theorem partition_cuts (thresholds : List ℝ) (r : ℝ) : r ∈ thresholds → ∀ I ∈ thresholdPartition thresholds, cutAt r I := by induction thresholds with | nil => intro hr; simp at hr | cons t rest ih => intro hr rcases List.mem_cons.mp hr with h | h · subst r; exact splitAll_new_cuts (thresholdPartition rest) t · exact splitAll_preserves_cuts (thresholdPartition rest) t r (ih h)
theorem sumOnIntervals_congr (f g : ThresholdInterval → ℝ) (intervals : List ThresholdInterval) : (∀ I ∈ intervals, f I = g I) → sumOnIntervals f intervals = sumOnIntervals g intervals := by induction intervals with | nil => intro _; rfl | cons J rest ih => intro h have hJ := h J (by simp) have hr : ∀ I ∈ rest, f I = g I := fun I hI => h I (by simp [hI]) simp only [sumOnIntervals, hJ, ih hr]
theorem partition_acceptance_mass (thresholds : List ℝ) (r : ℝ) (hr : r ∈ thresholds) (h0 : 0 ≤ r) (h1 : r ≤ 1) : sumOnIntervals (fun I => if I.lo < r then I.hi - I.lo else 0) (thresholdPartition thresholds) = r := by calc _ = sumOnIntervals (intervalCDF r) (thresholdPartition thresholds) := sumOnIntervals_congr _ _ _ (fun I hI => accepted_interval_mass I r (partition_cuts thresholds r hr I hI)) _ = r := partition_cdf thresholds r h0 h1
theorem sum_interval_get (f : ThresholdInterval → ℝ) (intervals : List ThresholdInterval) : (∑ i : Fin intervals.length, f intervals[i]) = sumOnIntervals f intervals := by induction intervals with | nil => simp [sumOnIntervals] | cons I rest ih => simpa [Fin.sum_univ_succ, sumOnIntervals] using congrArg (fun x : ℝ => f I + x) ih
variable {α : Type*} [Fintype α]
private theorem sum_div_const {ι : Type*} [Fintype ι] (f : ι → ℝ) (c : ℝ) : (∑ i, f i) / c = ∑ i, f i / c := by simp only [div_eq_mul_inv, Finset.sum_mul]
abbrev RectangleSeed (thresholds : List ℝ) (α : Type*) := α × Fin (thresholdPartition thresholds).length
def rectangleWeight (thresholds : List ℝ) (seed : RectangleSeed thresholds α) : ℝ := ((thresholdPartition thresholds)[seed.2].hi - (thresholdPartition thresholds)[seed.2].lo) / (Fintype.card α : ℝ)
def rectangleAccept (thresholds : List ℝ) (density : α → ℝ) (seed : RectangleSeed thresholds α) : Bool := decide ((thresholdPartition thresholds)[seed.2].lo < density seed.1)
theorem rectangleWeight_nonnegative (thresholds : List ℝ) (seed : RectangleSeed thresholds α) : 0 ≤ rectangleWeight thresholds seed := div_nonneg (sub_nonneg.mpr ((thresholdPartition thresholds)[seed.2].valid)) (by positivity)
theorem rectangleWeight_normalized [Nonempty α] (thresholds : List ℝ) : ∑ seed : RectangleSeed thresholds α, rectangleWeight thresholds seed = 1 := by rw [Fintype.sum_prod_type] have hrow (a : α) : (∑ i, rectangleWeight thresholds (a, i)) = 1 / (Fintype.card α : ℝ) := by unfold rectangleWeight rw [← sum_div_const, sum_interval_get (fun I => I.hi - I.lo), partition_total_mass] simp_rw [hrow] have hc : (Fintype.card α : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero simp [hc]
def rectangleDistribution [Nonempty α] (thresholds : List ℝ) : Games.FiniteDistribution (RectangleSeed thresholds α) where weight := rectangleWeight thresholds nonnegative := rectangleWeight_nonnegative thresholds normalized := rectangleWeight_normalized thresholds
theorem rectangle_row_mass (thresholds : List ℝ) (density : α → ℝ) (a : α) (hm : density a ∈ thresholds) (h0 : 0 ≤ density a) (h1 : density a ≤ 1) : (∑ i, if rectangleAccept thresholds density (a, i) then rectangleWeight thresholds (a, i) else 0) = density a / (Fintype.card α : ℝ) := by calc _ = (∑ i : Fin (thresholdPartition thresholds).length, if (thresholdPartition thresholds)[i].lo < density a then (thresholdPartition thresholds)[i].hi - (thresholdPartition thresholds)[i].lo else 0) / (Fintype.card α : ℝ) := by rw [sum_div_const] apply Finset.sum_congr rfl intro i _ simp [rectangleAccept, rectangleWeight, ite_div] _ = density a / (Fintype.card α : ℝ) := by rw [sum_interval_get (fun I => if I.lo < density a then I.hi - I.lo else 0), partition_acceptance_mass thresholds (density a) hm h0 h1]
theorem rectangle_acceptance_mass (thresholds : List ℝ) (density : α → ℝ) (hm : ∀ a, density a ∈ thresholds) (h0 : ∀ a, 0 ≤ density a) (h1 : ∀ a, density a ≤ 1) : eventMass (rectangleWeight thresholds) (rectangleAccept thresholds density) = (∑ a, density a) / (Fintype.card α : ℝ) := by unfold eventMass rw [Fintype.sum_prod_type] simp_rw [rectangle_row_mass thresholds density _ (hm _) (h0 _) (h1 _)] rw [sum_div_const]
theorem rectangle_label_mass [DecidableEq α] (thresholds : List ℝ) (density : α → ℝ) (a : α) (hm : ∀ x, density x ∈ thresholds) (h0 : ∀ x, 0 ≤ density x) (h1 : ∀ x, density x ≤ 1) : eventMass (rectangleWeight thresholds) (fun seed => rectangleAccept thresholds density seed && decide (seed.1 = a)) = density a / (Fintype.card α : ℝ) := by unfold eventMass rw [Fintype.sum_prod_type] calc _ = ∑ x : α, if x = a then density x / (Fintype.card α : ℝ) else 0 := by apply Finset.sum_congr rfl intro x _ by_cases hx : x = a · simpa [hx] using rectangle_row_mass thresholds density x (hm x) (h0 x) (h1 x) · simp [hx] _ = density a / (Fintype.card α : ℝ) := by simp
omit [Fintype α] in theorem rectangle_and (thresholds : List ℝ) (p q : α → ℝ) : (fun seed => rectangleAccept thresholds p seed && rectangleAccept thresholds q seed) = rectangleAccept thresholds (fun a => min (p a) (q a)) := by funext seed simp [rectangleAccept]
omit [Fintype α] in theorem rectangle_or (thresholds : List ℝ) (p q : α → ℝ) : (fun seed => rectangleAccept thresholds p seed || rectangleAccept thresholds q seed) = rectangleAccept thresholds (fun a => max (p a) (q a)) := by funext seed simp [rectangleAccept]
theorem min_mem_thresholds (thresholds : List ℝ) {x y : ℝ} (hx : x ∈ thresholds) (hy : y ∈ thresholds) : min x y ∈ thresholds := by by_cases h : x ≤ y <;> simp [min_def, h, hx, hy]
theorem max_mem_thresholds (thresholds : List ℝ) {x y : ℝ} (hx : x ∈ thresholds) (hy : y ∈ thresholds) : max x y ∈ thresholds := by by_cases h : x ≤ y <;> simp [max_def, h, hx, hy]
theorem rectangle_union_mass (thresholds : List ℝ) (p q : α → ℝ) (hpm : ∀ a, p a ∈ thresholds) (hqm : ∀ a, q a ∈ thresholds) (hp0 : ∀ a, 0 ≤ p a) (_hq0 : ∀ a, 0 ≤ q a) (hp1 : ∀ a, p a ≤ 1) (hq1 : ∀ a, q a ≤ 1) : eventMass (rectangleWeight thresholds) (fun seed => rectangleAccept thresholds p seed || rectangleAccept thresholds q seed) = unionMass p q / (Fintype.card α : ℝ) := by rw [rectangle_or] exact rectangle_acceptance_mass thresholds _ (fun a => max_mem_thresholds thresholds (hpm a) (hqm a)) (fun a => (hp0 a).trans (le_max_left _ _)) (fun a => max_le (hp1 a) (hq1 a))
theorem rectangle_common_label_mass [DecidableEq α] (thresholds : List ℝ) (p q : α → ℝ) (a : α) (hpm : ∀ x, p x ∈ thresholds) (hqm : ∀ x, q x ∈ thresholds) (hp0 : ∀ x, 0 ≤ p x) (hq0 : ∀ x, 0 ≤ q x) (hp1 : ∀ x, p x ≤ 1) (_hq1 : ∀ x, q x ≤ 1) : eventMass (rectangleWeight thresholds) (fun seed => (rectangleAccept thresholds p seed && rectangleAccept thresholds q seed) && decide (seed.1 = a)) = min (p a) (q a) / (Fintype.card α : ℝ) := by have hand := congrFun (rectangle_and thresholds p q) simp_rw [hand] exact rectangle_label_mass thresholds _ a (fun x => min_mem_thresholds thresholds (hpm x) (hqm x)) (fun x => le_min (hp0 x) (hq0 x)) (fun x => (min_le_left _ _).trans (hp1 x))
end
end MinUncutGames.Foundations.CorrelatedSampling
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733import Mathlibimport OAI.Computability.MinUncut.Games.FinalCNFPatternimport OAI.Computability.MinUncut.Machines.RawInitialMachineFinish
namespace OAI
namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
open Turingopen PCP.AlphabetTable
def headerFrame (input archive vertices darts rowIndex tail head accumulator : List Bool) : Tape → List Bool | .input => input | .archive => archive | .vertices => vertices | .darts => darts | .rowIndex => rowIndex | .tail => tail | .head => head | .accumulator => accumulator | _ => []
def headerInputTapes (input : List Bool) : Tape → List Bool := headerFrame input [] [] [] [] [] [] []
def headerResultTapes (n m : Nat) (rowsBits : List Bool) : Tape → List Bool := headerFrame rowsBits (encodeWords [n, m] ++ rowsBits) (encodeWord n) (encodeWord m) (encodeWord 0) [] [] (encodeWords [6 * n + 36864 * m, 40960 * m]).reverse
@[simp] theorem headerResultTapes_input (n m : Nat) (rowsBits : List Bool) : headerResultTapes n m rowsBits .input = rowsBits := rfl
@[simp] theorem headerResultTapes_archive (n m : Nat) (rowsBits : List Bool) : headerResultTapes n m rowsBits .archive = encodeWords [n, m] ++ rowsBits := rfl
@[simp] theorem headerResultTapes_accumulator (n m : Nat) (rowsBits : List Bool) : headerResultTapes n m rowsBits .accumulator = (encodeWords [6 * n + 36864 * m, 40960 * m]).reverse := rfl
@[simp] theorem headerResultTapes_rowIndex (n m : Nat) (rowsBits : List Bool) : headerResultTapes n m rowsBits .rowIndex = encodeWord 0 := rfl
noncomputable def headerTimePolynomial : Polynomial Nat := Polynomial.C 25 * Polynomial.X + Polynomial.C 52
@[simp] theorem headerTimePolynomial_eval (length : Nat) : headerTimePolynomial.eval length = 25 * length + 52 := by simp [headerTimePolynomial]
def headerInTime (rowPlan : Plan) (n m : Nat) (rowsBits : List Bool) (ambient : Ambient) : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some .copyFirst, ((ambient, ()), none), headerInputTapes (encodeWords [n, m] ++ rowsBits)⟩ (some ⟨some .guard, ((ambient, ()), none), headerResultTapes n m rowsBits⟩) (headerTimePolynomial.eval (encodeWords [n, m] ++ rowsBits).length) := by let word := encodeWords [n, m] ++ rowsBits let bits := encodeWords [6 * n + 36864 * m, 40960 * m] let b₀ := headerInputTapes word let b₁ := headerFrame word word [] [] [] [] [] [] let b₂ := headerFrame (encodeWord m ++ rowsBits) word (encodeWord n) [] [] [] [] [] let b₃ := headerFrame rowsBits word (encodeWord n) (encodeWord m) [] [] [] [] let b₄ := headerFrame rowsBits word (encodeWord n) (encodeWord m) (encodeWord 0) (encodeWord 0) (encodeWord 0) [] let b₅ := headerFrame rowsBits word (encodeWord n) (encodeWord m) (encodeWord 0) (encodeWord 0) (encodeWord 0) bits.reverse let b₆ := headerFrame rowsBits word (encodeWord n) (encodeWord m) (encodeWord 0) [] (encodeWord 0) bits.reverse let b₇ := headerResultTapes n m rowsBits have h₀ : Function.update b₀ Tape.archive (b₀ .input ++ b₀ .archive) = b₁ := by funext tape; cases tape <;> simp [b₀, b₁, headerInputTapes, headerFrame] have h₁ : Hastad.SourceMachine.fieldTapes Tape.input Tape.vertices b₁ (encodeWord m ++ rowsBits) (encodeWord n ++ b₁ .vertices) = b₂ := by funext tape; cases tape <;> simp [Hastad.SourceMachine.fieldTapes, b₁, b₂, headerFrame] have h₂ : Hastad.SourceMachine.fieldTapes Tape.input Tape.darts b₂ rowsBits (encodeWord m ++ b₂ .darts) = b₃ := by funext tape; cases tape <;> simp [Hastad.SourceMachine.fieldTapes, b₂, b₃, headerFrame] have h₄ : Emitter.resultTapes Tape.accumulator b₄ (Emitter.prefixBits (Emitter.listCommands headerPlan) (values n m 0 0 0) ambient headerPlan.length) = b₅ := by rw [Emitter.bits_listCommands, headerPlan_bits] funext tape; cases tape <;> simp [Emitter.resultTapes, b₄, b₅, bits, headerFrame] have h₅ : Function.update b₅ Tape.tail [] = b₆ := by funext tape; cases tape <;> simp [b₅, b₆, headerFrame] have h₆ : Function.update b₆ Tape.head [] = b₇ := by funext tape; cases tape <;> simp [b₆, b₇, headerResultTapes, bits, word, headerFrame] have hn : n ≤ word.length := by simp only [word, List.length_append, encodeWords_length, List.sum_cons, List.sum_nil, List.length_cons, List.length_nil] ; omega have hm : m ≤ word.length := by simp only [word, List.length_append, encodeWords_length, List.sum_cons, List.sum_nil, List.length_cons, List.length_nil] ; omega let p₀ := MachineCopy.copyInTime Tape.input Tape.archive Tape.scratch (by decide) (by decide) (by decide) false .copyFirst .copySecond (some .startVertices) (program headerPlan rowPlan) rfl rfl b₀ (by rfl) (ambient, ()) none have p₀' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some .copyFirst, ((ambient, ()), none), b₀⟩ (some ⟨some .startVertices, ((ambient, ()), none), b₁⟩) (2 * (word.length + 1)) := by have h := p₀ rw [h₀] at h simpa only [show b₀ .input = word from rfl] using h let p₁ := Hastad.SourceMachine.fieldInTime Tape.input Tape.vertices (by decide) .startVertices .readVertices (some .startDarts) (program headerPlan rowPlan) rfl rfl b₁ n (encodeWord m ++ rowsBits) (by simp [b₁, headerFrame, word, encodeWords, List.append_assoc]) (ambient, ()) none have p₁' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some .startVertices, ((ambient, ()), none), b₁⟩ (some ⟨some .startDarts, ((ambient, ()), none), b₂⟩) (n + 2) := by simpa only [h₁] using p₁ let p₂ := Hastad.SourceMachine.fieldInTime Tape.input Tape.darts (by decide) .startDarts .readDarts (some .seedIndex) (program headerPlan rowPlan) rfl rfl b₂ m rowsBits rfl (ambient, ()) none have p₂' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some .startDarts, ((ambient, ()), none), b₂⟩ (some ⟨some .seedIndex, ((ambient, ()), none), b₃⟩) (m + 2) := by simpa only [h₂] using p₂ let p₃ : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some .seedIndex, ((ambient, ()), none), b₃⟩ (some ⟨some (.header (Emitter.labelAt headerPlan.length 36864 0 .entry)), ((ambient, ()), none), b₄⟩) 1 := { steps := 1 evals_in_steps := by simp only [Function.iterate_one] change TM2.step (program headerPlan rowPlan) ⟨some .seedIndex, ((ambient, ()), none), b₃⟩ = _ have ht : Function.update (Function.update (Function.update b₃ Tape.rowIndex [false]) Tape.tail [false]) Tape.head [false] = b₄ := by funext tape; cases tape <;> simp [b₃, b₄, headerFrame, encodeWord] simp only [TM2.step, program, TM2.stepAux] apply congrArg some exact congrArg (TM2.Cfg.mk _ _) ht steps_le_m := Nat.le_refl _ } let p₄ := Emitter.planInTime (Emitter.listCommands headerPlan) source Tape.scratch Tape.accumulator source_ne_scratch source_ne_accumulator (by decide) Label.header (some .headerClearTail) (program headerPlan rowPlan) (fun _ => rfl) (values n m 0 0 0) b₄ (by intro i; fin_cases i <;> rfl) rfl ambient word.length (by intro i fin_cases i · exact hn · exact hm · exact Nat.zero_le _ · exact Nat.zero_le _ · exact Nat.zero_le _) have p₄' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some (.header (Emitter.labelAt headerPlan.length 36864 0 .entry)), ((ambient, ()), none), b₄⟩ (some ⟨some .headerClearTail, ((ambient, ()), none), b₅⟩) (7 * (3 * (word.length + 1) + 3) + 1) := by have h := p₄ rw [h₄] at h simpa only [headerPlan_length] using h let p₅ := MachineLookup.discardInTime Tape.tail .headerClearTail .headerClearHead (program headerPlan rowPlan) rfl b₅ 0 [] (by simp [b₅, headerFrame]) (ambient, ()) none have p₅' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some .headerClearTail, ((ambient, ()), none), b₅⟩ (some ⟨some .headerClearHead, ((ambient, ()), none), b₆⟩) 1 := by simpa only [h₅] using p₅ let p₆ := MachineLookup.discardInTime Tape.head .headerClearHead .guard (program headerPlan rowPlan) rfl b₆ 0 [] (by simp [b₆, headerFrame]) (ambient, ()) none have p₆' : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some .headerClearHead, ((ambient, ()), none), b₆⟩ (some ⟨some .guard, ((ambient, ()), none), b₇⟩) 1 := by simpa only [h₆] using p₆ let p₀₁ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀' p₁' let p₀₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁ p₂' let p₀₁₂₃ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁₂ p₃ let p₀₁₂₃₄ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁₂₃ p₄' let p₀₁₂₃₄₅ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁₂₃₄ p₅' let p := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀₁₂₃₄₅ p₆' exact { toEvalsTo := p.toEvalsTo steps_le_m := by have h := p.steps_le_m change _ ≤ headerTimePolynomial.eval word.length rw [headerTimePolynomial_eval] omega }
def tableRowsBits (table : PCP.GenericGraphTables.Table 64) : List Bool := encodeWords ((PCP.GenericGraphTables.rowList table).flatMap PCP.GenericGraphTables.rowWords)
theorem tableBits_header_rows (table : PCP.GenericGraphTables.Table 64) : PCP.GenericGraphTables.tableBits table = encodeWords [table.vertices, table.darts] ++ tableRowsBits table := by simp only [PCP.GenericGraphTables.tableBits, PCP.GenericGraphTables.tableWords, encodeWords_append, tableRowsBits]
def tableHeaderInTime (rowPlan : Plan) (table : PCP.GenericGraphTables.Table 64) (ambient : Ambient) : StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) ⟨some .copyFirst, ((ambient, ()), none), headerInputTapes (PCP.GenericGraphTables.tableBits table)⟩ (some ⟨some .guard, ((ambient, ()), none), headerResultTapes table.vertices table.darts (tableRowsBits table)⟩) (headerTimePolynomial.eval (PCP.GenericGraphTables.tableBits table).length) := by rw [tableBits_header_rows] exact headerInTime rowPlan table.vertices table.darts (tableRowsBits table) ambient
theorem headerInput_configuration (rowPlan : Plan) (input : List Bool) : initList (machine headerPlan rowPlan) input = ⟨some .copyFirst, ((((), fun _ => false), ()), none), headerInputTapes input⟩ := by have ht : (initList (machine headerPlan rowPlan) input).stk = headerInputTapes input := by funext tape cases tape <;> simp [initList, machine, headerInputTapes, headerFrame] all_goals rfl exact congrArg (TM2.Cfg.mk _ _) ht
def initializedTableHeaderInTime (rowPlan : Plan) (table : PCP.GenericGraphTables.Table 64) : StateTransition.EvalsToInTime (machine headerPlan rowPlan).step (initList (machine headerPlan rowPlan) (PCP.GenericGraphTables.tableBits table)) (some ⟨some .guard, ((((), fun _ => false), ()), none), headerResultTapes table.vertices table.darts (tableRowsBits table)⟩) (headerTimePolynomial.eval (PCP.GenericGraphTables.tableBits table).length) := by rw [headerInput_configuration] exact tableHeaderInTime rowPlan table ((), fun _ => false)
open Turing PCP PCP.AlphabetTable
def endpointTapes (base : Tape → List Bool) (tail reverse : Nat) (rest : List Bool) := Hastad.SourceMachine.fieldTapes Tape.input Tape.reverseIndex (Hastad.SourceMachine.fieldTapes Tape.input Tape.tail base (encodeWord reverse ++ rest) (encodeWord tail ++ base .tail)) rest (encodeWord reverse ++ base .reverseIndex)
def endpointsInTime (headerPlan plan : Plan) (base : Tape → List Bool) (tail reverse : Nat) (rest : List Bool) (hinput : base .input = encodeWord tail ++ encodeWord reverse ++ rest) (ambient : Ambient) : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some .startTail, ((ambient, ()), none), base⟩ (some ⟨some .headTableFirst, ((ambient, ()), none), endpointTapes base tail reverse rest⟩) (tail + reverse + 4) := by let first := Hastad.SourceMachine.fieldTapes Tape.input Tape.tail base (encodeWord reverse ++ rest) (encodeWord tail ++ base .tail) let run₁ := Hastad.SourceMachine.fieldInTime Tape.input Tape.tail (by decide) .startTail .readTail (some .startReverse) (program headerPlan plan) rfl rfl base tail (encodeWord reverse ++ rest) (by simpa only [List.append_assoc] using hinput) (ambient, ()) none have input₁ : first .input = encodeWord reverse ++ rest := by simp [first, Hastad.SourceMachine.fieldTapes] have reverse₁ : first .reverseIndex = base .reverseIndex := by simp [first, Hastad.SourceMachine.fieldTapes] let run₂ := Hastad.SourceMachine.fieldInTime Tape.input Tape.reverseIndex (by decide) .startReverse .readReverse (some .headTableFirst) (program headerPlan plan) rfl rfl first reverse rest input₁ (ambient, ()) none have joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ run₂ simpa only [first, reverse₁, endpointTapes, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] using joined
def relationInTime (headerPlan plan : Plan) (base : Tape → List Bool) (relation : GraphTables.RelationTable) (rest : List Bool) (hinput : base .input = encodeWords (GraphTables.relationWords relation) ++ rest) (ambient : Ambient) : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some .readRelation, ((ambient, ()), none), base⟩ (some ⟨some (.row (Emitter.labelAt plan.length 36864 0 .entry)), ((((), fun i => relation[i]), ()), none), Function.update base .input rest⟩) 1 where steps := 1 evals_in_steps := by change some (TM2.stepAux (program headerPlan plan .readRelation) _ _) = _ rw [program, stepAux_readRelationAt _ _ _ _ _ _ _ _ _ hinput] steps_le_m := Nat.le_refl _
def emitInTime (headerPlan plan : Plan) (base : Tape → List Bool) (operands : Fin 5 → Nat) (hoperands : ∀ i, base (source i) = encodeWord (operands i)) (hscratch : base .scratch = []) (ambient : Ambient) (N : Nat) (hbounded : ∀ i, operands i ≤ N) : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some (.row (Emitter.labelAt plan.length 36864 0 .entry)), ((ambient, ()), none), base⟩ (some ⟨some .clearTail, ((ambient, ()), none), Function.update base .accumulator ((plan.flatMap (Emitter.commandBits operands ambient)).reverse ++ base .accumulator)⟩) (plan.length * (3 * (N + 1) + 3) + 1) := by have run := Emitter.planInTime (Emitter.listCommands plan) source Tape.scratch Tape.accumulator source_ne_scratch source_ne_accumulator (by decide) Label.row (some .clearTail) (program headerPlan plan) (fun _ => rfl) operands base hoperands hscratch ambient N hbounded simpa only [Emitter.bits_listCommands, Emitter.resultTapes] using run
def finishTapes (base : Tape → List Bool) (row : Nat) : Tape → List Bool := Function.update (Function.update (Function.update (Function.update base Tape.tail []) Tape.head []) Tape.reverseIndex []) Tape.rowIndex (encodeWord (row + 1))
def finishInTime (headerPlan plan : Plan) (base : Tape → List Bool) (tail head reverse row : Nat) (htail : base .tail = encodeWord tail) (hhead : base .head = encodeWord head) (hreverse : base .reverseIndex = encodeWord reverse) (hrow : base .rowIndex = encodeWord row) (ambient : Ambient) : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some .clearTail, ((ambient, ()), none), base⟩ (some ⟨some .guard, ((ambient, ()), none), finishTapes base row⟩) (tail + head + reverse + 4) := by let t₁ := Function.update base Tape.tail [] let t₂ := Function.update t₁ Tape.head [] let t₃ := Function.update t₂ Tape.reverseIndex [] let run₁ := MachineLookup.discardInTime Tape.tail .clearTail .clearHead (program headerPlan plan) rfl base tail [] (by simpa using htail) (ambient, ()) none have hhead₁ : t₁ .head = encodeWord head := by simp [t₁, hhead] let run₂ := MachineLookup.discardInTime Tape.head .clearHead .clearReverse (program headerPlan plan) rfl t₁ head [] (by simpa using hhead₁) (ambient, ()) none have hreverse₂ : t₂ .reverseIndex = encodeWord reverse := by simp [t₂, t₁, hreverse] let run₃ := MachineLookup.discardInTime Tape.reverseIndex .clearReverse .nextRow (program headerPlan plan) rfl t₂ reverse [] (by simpa using hreverse₂) (ambient, ()) none let run₄ : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some .nextRow, ((ambient, ()), none), t₃⟩ (some ⟨some .guard, ((ambient, ()), none), finishTapes base row⟩) 1 := { steps := 1 evals_in_steps := by change some (TM2.stepAux (program headerPlan plan .nextRow) _ _) = _ simp only [program, TM2.stepAux] congr 2 simp [t₃, t₂, t₁, finishTapes, hrow, encodeWord, List.replicate_succ] steps_le_m := Nat.le_refl _ } let r₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ run₂ let r₁₂₃ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂ run₃ have run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂₃ run₄ simpa only [Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] using run
end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
namespace MinUncutGames.Foundations.Complexity.FinalCNFTableAdapter
open PCP
def genericRow {n m : Nat} (row : GraphTables.DartRow n m) : GenericGraphTables.DartRow 64 n m := ⟨row.tail, row.reverseIndex, row.relation⟩
@[simp] theorem genericRow_tail {n m : Nat} (row : GraphTables.DartRow n m) : (genericRow row).tail = row.tail := rfl
@[simp] theorem genericRow_reverseIndex {n m : Nat} (row : GraphTables.DartRow n m) : (genericRow row).reverseIndex = row.reverseIndex := rfl
@[simp] theorem genericRow_relation {n m : Nat} (row : GraphTables.DartRow n m) : (genericRow row).relation = row.relation := rfl
def genericRows {n m : Nat} (rows : GraphTables.Rows n m) : GenericGraphTables.Rows 64 n m := rows.map genericRow
@[simp] theorem genericRows_get {n m : Nat} (rows : GraphTables.Rows n m) (e : Fin m) : (genericRows rows)[e] = genericRow rows[e] := by simp [genericRows]
@[simp] theorem genericRows_reverseAt {n m : Nat} (rows : GraphTables.Rows n m) (e : Fin m) : GenericGraphTables.reverseAt (genericRows rows) e = GraphTables.reverseAt rows e := by change (genericRows rows)[e].reverseIndex = rows[e].reverseIndex rw [genericRows_get] rfl
@[simp] theorem genericRows_acceptsAt {n m : Nat} (rows : GraphTables.Rows n m) (e : Fin m) (a b : Fin 64) : GenericGraphTables.acceptsAt (genericRows rows) e a b = GraphTables.acceptsAt rows e a b := by simp only [GenericGraphTables.acceptsAt, genericRows_get, genericRow_relation] rfl
theorem genericRows_valid {n m : Nat} (rows : GraphTables.Rows n m) (valid : GraphTables.Valid rows) : GenericGraphTables.Valid (genericRows rows) := by constructor · intro e simpa only [genericRows_reverseAt] using valid.1 e · intro e a b simpa only [genericRows_reverseAt, genericRows_acceptsAt] using valid.2 e a b
def genericTable (table : GraphTables.Table) : GenericGraphTables.Table 64 where vertices := table.vertices darts := table.darts rows := genericRows table.rows valid := genericRows_valid table.rows table.valid
@[simp] theorem genericTable_vertices (table : GraphTables.Table) : (genericTable table).vertices = table.vertices := rfl
@[simp] theorem genericTable_darts (table : GraphTables.Table) : (genericTable table).darts = table.darts := rfl
@[simp] theorem genericTable_row (table : GraphTables.Table) (e : Fin table.darts) : (genericTable table).rows[e] = genericRow table.rows[e] := genericRows_get _ _
@[simp] theorem genericTable_tail (table : GraphTables.Table) (e : Fin table.darts) : (genericTable table).rows[e].tail = table.rows[e].tail := by rw [genericTable_row] rfl
@[simp] theorem genericTable_reverseIndex (table : GraphTables.Table) (e : Fin table.darts) : (genericTable table).rows[e].reverseIndex = table.rows[e].reverseIndex := by rw [genericTable_row] rfl
@[simp] theorem genericTable_relation (table : GraphTables.Table) (e : Fin table.darts) : (genericTable table).rows[e].relation = table.rows[e].relation := by rw [genericTable_row] rfl
@[simp] theorem genericRow_words {n m : Nat} (row : GraphTables.DartRow n m) : GenericGraphTables.rowWords (genericRow row) = GraphTables.rowWords row := rfl
theorem genericTable_rowList (table : GraphTables.Table) : GenericGraphTables.rowList (genericTable table) = (GraphTables.rowList table).map genericRow := by simp only [GenericGraphTables.rowList, GraphTables.rowList, genericTable, genericRows, Vector.toList_map]
@[simp] theorem genericTable_tableWords (table : GraphTables.Table) : GenericGraphTables.tableWords (genericTable table) = GraphTables.tableWords table := by simp only [GenericGraphTables.tableWords, GraphTables.tableWords, genericTable_vertices, genericTable_darts, genericTable_rowList, List.flatMap_map, genericRow_words]
@[simp] theorem genericTable_tableBits (table : GraphTables.Table) : GenericGraphTables.tableBits (genericTable table) = GraphTables.tableBits table := by simp only [GenericGraphTables.tableBits, GraphTables.tableBits, genericTable_tableWords]
@[simp] theorem genericTable_semantics_tail (table : GraphTables.Table) (e : Fin table.darts) : (GenericGraphTables.semantics (genericTable table)).tail e = (GraphTables.semantics table).tail e := genericTable_tail table e
@[simp] theorem genericTable_semantics_reverse (table : GraphTables.Table) (e : Fin table.darts) : (GenericGraphTables.semantics (genericTable table)).reverse e = (GraphTables.semantics table).reverse e := genericTable_reverseIndex table e
@[simp] theorem genericTable_semantics_head (table : GraphTables.Table) (e : Fin table.darts) : (GenericGraphTables.semantics (genericTable table)).head e = (GraphTables.semantics table).head e := by simp only [ConstraintGraph.head, genericTable_semantics_reverse, genericTable_semantics_tail] rfl
@[simp] theorem genericTable_semantics_accepts (table : GraphTables.Table) (e : Fin table.darts) (a b : Fin 64) : (GenericGraphTables.semantics (genericTable table)).accepts e a b = (GraphTables.semantics table).accepts e a b := genericRows_acceptsAt _ _ _ _
@[simp] theorem genericTable_headIndex (table : GraphTables.Table) (e : Fin table.darts) : AlphabetTable.Lookup.headIndex (genericTable table) e = table.rows[e].reverseIndex := genericTable_reverseIndex table e
@[simp] theorem genericTable_headValue (table : GraphTables.Table) (e : Fin table.darts) : AlphabetTable.Lookup.headValue (genericTable table) e = ((GraphTables.semantics table).head e).val := by exact (AlphabetTable.Lookup.headValue_eq_semantics (genericTable table) e).trans (congrArg Fin.val (genericTable_semantics_head table e))
theorem genericTable_headValue_tableGraph (table : GraphTables.Table) (e : Fin table.darts) : AlphabetTable.Lookup.headValue (genericTable table) e = ((FinalCNFPattern.tableGraph table).head e).val := by rw [genericTable_headValue] rfl
theorem genericTable_pattern_relation (table : GraphTables.Table) (e : Fin table.darts) (p : VerifierToCNF.PatternIndex 12) : (genericTable table).rows[e].relation[FinalCNFPattern.patternRelationIndex p] = (FinalCNFPattern.tableVerifier table).accepts e (VerifierToCNF.patternAt 12 p) := by rw [genericTable_relation] exact FinalCNFPattern.pattern_lookup_eq_verifier_accepts table e p
end MinUncutGames.Foundations.Complexity.FinalCNFTableAdapter
namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
open Turing PCP PCP.AlphabetTable FinalCNFTableAdapter
@[simp] theorem headRoles_zero : headRoles 0 = Tape.archive := rfl@[simp] theorem headRoles_one : headRoles 1 = Tape.reverseIndex := rfl@[simp] theorem headRoles_two : headRoles 2 = Tape.scanWork := rfl@[simp] theorem headRoles_three : headRoles 3 = Tape.indexWork := rfl@[simp] theorem headRoles_four : headRoles 4 = Tape.head := rfl@[simp] theorem headRoles_five : headRoles 5 = Tape.scratch := rfl
def rowOperands (table : GraphTables.Table) (e : Fin table.darts) : Fin 5 → Nat := values table.vertices table.darts table.rows[e].tail.val table.rows[table.rows[e].reverseIndex].tail.val e.val
def rowRelation (table : GraphTables.Table) (e : Fin table.darts) : Ambient := ((), fun i => table.rows[e].relation[i])
def rowRest (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : List Bool := encodeWords (GraphTables.relationWords table.rows[e].relation) ++ rest
def preparedTapes (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : Tape → List Bool := Lookup.headLookupTapes headRoles (endpointTapes base table.rows[e].tail.val table.rows[e].reverseIndex.val (rowRest table e rest)) (genericTable table) e
theorem prepared_input (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : preparedTapes base table e rest .input = rowRest table e rest := by simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, endpointTapes, Hastad.SourceMachine.fieldTapes]
theorem prepared_head (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : preparedTapes base table e rest .head = encodeWord table.rows[table.rows[e].reverseIndex].tail.val := by simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, genericTable_headValue, GraphTables.semantics, ConstraintGraph.head, GraphTables.reverseAt]
theorem prepared_tail (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : preparedTapes base table e rest .tail = encodeWord table.rows[e].tail.val ++ base .tail := by simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, endpointTapes, Hastad.SourceMachine.fieldTapes]
theorem prepared_reverse (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : preparedTapes base table e rest .reverseIndex = encodeWord table.rows[e].reverseIndex.val ++ base .reverseIndex := by simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, endpointTapes, Hastad.SourceMachine.fieldTapes]
theorem prepared_frame (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) (tape : Tape) (hi : tape ≠ .input) (ht : tape ≠ .tail) (hr : tape ≠ .reverseIndex) (hh : tape ≠ .head) (hs : tape ≠ .scanWork) (hx : tape ≠ .indexWork) : preparedTapes base table e rest tape = base tape := by simp [preparedTapes, Lookup.headLookupTapes, MachineLookup.tapes, endpointTapes, Hastad.SourceMachine.fieldTapes, hi, ht, hr, hh, hs, hx]
def emittedTapes (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : Tape → List Bool := Function.update (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.accumulator ((plan.flatMap (Emitter.commandBits (rowOperands table e) (rowRelation table e))).reverse ++ base .accumulator)
def rowResultTapes (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : Tape → List Bool := finishTapes (emittedTapes plan base table e rest) e.val
@[simp] theorem rowResult_input (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : rowResultTapes plan base table e rest .input = rest := by simp [rowResultTapes, finishTapes, emittedTapes]
@[simp] theorem rowResult_tail (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : rowResultTapes plan base table e rest .tail = [] := by simp [rowResultTapes, finishTapes]
@[simp] theorem rowResult_head (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : rowResultTapes plan base table e rest .head = [] := by simp [rowResultTapes, finishTapes]
@[simp] theorem rowResult_reverse (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : rowResultTapes plan base table e rest .reverseIndex = [] := by simp [rowResultTapes, finishTapes]
@[simp] theorem rowResult_index (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : rowResultTapes plan base table e rest .rowIndex = encodeWord (e.val + 1) := by simp [rowResultTapes, finishTapes]
@[simp] theorem rowResult_accumulator (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) : rowResultTapes plan base table e rest .accumulator = (plan.flatMap (Emitter.commandBits (rowOperands table e) (rowRelation table e))).reverse ++ base .accumulator := by simp [rowResultTapes, finishTapes, emittedTapes]
theorem rowResult_frame (plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) (tape : Tape) (hi : tape ≠ .input) (ht : tape ≠ .tail) (hr : tape ≠ .reverseIndex) (hh : tape ≠ .head) (hs : tape ≠ .scanWork) (hx : tape ≠ .indexWork) (ha : tape ≠ .accumulator) (hc : tape ≠ .rowIndex) : rowResultTapes plan base table e rest tape = base tape := by simp only [rowResultTapes, finishTapes, emittedTapes, Function.update_of_ne hi, Function.update_of_ne ht, Function.update_of_ne hr, Function.update_of_ne hh, Function.update_of_ne ha, Function.update_of_ne hc] exact prepared_frame base table e rest tape hi ht hr hh hs hx
def guardRowInTime (headerPlan plan : Plan) (base : Tape → List Bool) (ambient : Ambient) (hinput : base .input ≠ []) : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some .guard, ((ambient, ()), none), base⟩ (some ⟨some .startTail, ((ambient, ()), none), base⟩) 1 where steps := 1 evals_in_steps := by change some (TM2.stepAux (program headerPlan plan .guard) _ _) = _ cases hb : base .input with | nil => exact False.elim (hinput hb) | cons b bs => simp [program, guard, TM2.stepAux, hb] steps_le_m := Nat.le_refl _
def guardEndInTime (headerPlan plan : Plan) (base : Tape → List Bool) (ambient : Ambient) (hinput : base .input = []) : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some .guard, ((ambient, ()), none), base⟩ (some ⟨some .reverseOutput, ((ambient, ()), none), base⟩) 1 where steps := 1 evals_in_steps := by change some (TM2.stepAux (program headerPlan plan .guard) _ _) = _ simp [program, guard, TM2.stepAux, hinput] steps_le_m := Nat.le_refl _
theorem prepared_operands (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) (hn : base .vertices = encodeWord table.vertices) (hm : base .darts = encodeWord table.darts) (hr : base .rowIndex = encodeWord e.val) (ht : base .tail = []) : ∀ i, (Function.update (preparedTapes base table e rest) Tape.input rest) (source i) = encodeWord (rowOperands table e i) := by intro i fin_cases i · simpa [source, rowOperands, values] using prepared_frame base table e rest .vertices (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) |>.trans hn · change (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.darts = _ simp only [Function.update_of_ne (show Tape.darts ≠ Tape.input by decide)] exact (prepared_frame base table e rest .darts (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)).trans hm · change (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.tail = _ simp only [Function.update_of_ne (show Tape.tail ≠ Tape.input by decide), prepared_tail, ht, List.append_nil] rfl · change (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.head = _ simp only [Function.update_of_ne (show Tape.head ≠ Tape.input by decide), prepared_head] rfl · change (Function.update (preparedTapes base table e rest) Tape.input rest) Tape.rowIndex = _ simp only [Function.update_of_ne (show Tape.rowIndex ≠ Tape.input by decide)] exact (prepared_frame base table e rest .rowIndex (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)).trans hr
theorem rowOperands_bounded (table : GraphTables.Table) (e : Fin table.darts) : ∀ i, rowOperands table e i ≤ (GraphTables.tableBits table).length := by intro i fin_cases i · exact GraphTables.vertices_le_tableBits_length table · exact GraphTables.darts_le_tableBits_length table · exact table.rows[e].tail.isLt.le.trans (GraphTables.vertices_le_tableBits_length table) · exact table.rows[table.rows[e].reverseIndex].tail.isLt.le.trans (GraphTables.vertices_le_tableBits_length table) · exact e.isLt.le.trans (GraphTables.darts_le_tableBits_length table)
def rowTime (plan : Plan) (N : Nat) : Nat := plan.length * (3 * (N + 1) + 3) + 12 * N + 15
noncomputable def rowInTime (headerPlan plan : Plan) (base : Tape → List Bool) (table : GraphTables.Table) (e : Fin table.darts) (rest : List Bool) (hinput : base .input = encodeWords (GraphTables.rowWords table.rows[e]) ++ rest) (harchive : base .archive = GraphTables.tableBits table) (hn : base .vertices = encodeWord table.vertices) (hm : base .darts = encodeWord table.darts) (hrow : base .rowIndex = encodeWord e.val) (ht : base .tail = []) (hh : base .head = []) (hr : base .reverseIndex = []) (hscratch : base .scratch = []) (ambient : Ambient) : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some .startTail, ((ambient, ()), none), base⟩ (some ⟨some .guard, ((rowRelation table e, ()), none), rowResultTapes plan base table e rest⟩) (rowTime plan (GraphTables.tableBits table).length) := by let parsed := endpointTapes base table.rows[e].tail.val table.rows[e].reverseIndex.val (rowRest table e rest) let ready := preparedTapes base table e rest let read := Function.update ready Tape.input rest let output := emittedTapes plan base table e rest let run₁ := endpointsInTime headerPlan plan base table.rows[e].tail.val table.rows[e].reverseIndex.val (rowRest table e rest) (by simpa [GraphTables.rowWords, encodeWords, List.append_assoc, rowRest] using hinput) ambient have parsed_archive : parsed .archive = GenericGraphTables.tableBits (genericTable table) := by simpa [parsed, endpointTapes, Hastad.SourceMachine.fieldTapes] using harchive have parsed_reverse : parsed .reverseIndex = encodeWord (Lookup.headIndex (genericTable table) e).val := by simp [parsed, endpointTapes, Hastad.SourceMachine.fieldTapes, hr] have parsed_head : parsed .head = [] := by simp [parsed, endpointTapes, Hastad.SourceMachine.fieldTapes, hh] have parsed_scratch : parsed .scratch = [] := by simp [parsed, endpointTapes, Hastad.SourceMachine.fieldTapes, hscratch] let run₂ := headPhaseInTime headerPlan plan parsed (genericTable table) e parsed_archive parsed_reverse parsed_head parsed_scratch ambient let run₃ := relationInTime headerPlan plan ready table.rows[e].relation rest (prepared_input base table e rest) ambient have read_operands : ∀ i, read (source i) = encodeWord (rowOperands table e i) := prepared_operands base table e rest hn hm hrow ht have read_scratch : read .scratch = [] := by simp only [read, Function.update_of_ne (show Tape.scratch ≠ Tape.input by decide)] exact (prepared_frame base table e rest .scratch (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)).trans hscratch have read_acc : read .accumulator = base .accumulator := by simp only [read, Function.update_of_ne (show Tape.accumulator ≠ Tape.input by decide)] exact prepared_frame base table e rest .accumulator (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) have run₄ : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some (.row (Emitter.labelAt plan.length 36864 0 .entry)), ((rowRelation table e, ()), none), read⟩ (some ⟨some .clearTail, ((rowRelation table e, ()), none), output⟩) (plan.length * (3 * ((GraphTables.tableBits table).length + 1) + 3) + 1) := by simpa only [read_acc, output, emittedTapes, read, ready] using emitInTime headerPlan plan read (rowOperands table e) read_operands read_scratch (rowRelation table e) (GraphTables.tableBits table).length (rowOperands_bounded table e) have output_tail : output .tail = encodeWord table.rows[e].tail.val := by simp [output, emittedTapes, prepared_tail, ht] have output_head : output .head = encodeWord table.rows[table.rows[e].reverseIndex].tail.val := by simp [output, emittedTapes, prepared_head] have output_reverse : output .reverseIndex = encodeWord table.rows[e].reverseIndex.val := by simp [output, emittedTapes, prepared_reverse, hr] have output_row : output .rowIndex = encodeWord e.val := by simp only [output, emittedTapes, Function.update_of_ne (show Tape.rowIndex ≠ Tape.accumulator by decide), Function.update_of_ne (show Tape.rowIndex ≠ Tape.input by decide)] exact (prepared_frame base table e rest .rowIndex (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)).trans hrow let run₅ := finishInTime headerPlan plan output table.rows[e].tail.val table.rows[table.rows[e].reverseIndex].tail.val table.rows[e].reverseIndex.val e.val output_tail output_head output_reverse output_row (rowRelation table e) let r₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ run₂ let r₁₂₃ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂ run₃ let r₁₂₃₄ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂₃ run₄ let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ r₁₂₃₄ run₅ refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } have hb := run.steps_le_m have htbound := rowOperands_bounded table e 2 have hhbound := rowOperands_bounded table e 3 have hrbound := table.rows[e].reverseIndex.isLt.le.trans (GraphTables.darts_le_tableBits_length table) change table.rows[e].tail.val ≤ _ at htbound change table.rows[table.rows[e].reverseIndex].tail.val ≤ _ at hhbound simp only [Lookup.headTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, genericTable_tableBits] at hb unfold rowTime omega
end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406import Mathlibimport OAI.Computability.MinUncut.PCP.PoweringFinalConstantsimport OAI.Computability.MinUncut.Games.FinalCNFStream
namespace OAI
namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
open PCP PCP.AlphabetTable
def formulaHeader (table : GraphTables.Table) : List Bool := encodeWords [6 * table.vertices + 36864 * table.darts, 40960 * table.darts]
theorem formulaHeader_eq (table : GraphTables.Table) : formulaHeader table = encodeWords [(FinalTableFormula.output table).«variables», (FinalTableFormula.output table).clauses.length] := by simp only [formulaHeader, FinalTableFormula.variable_count, FinalTableFormula.clause_count, Nat.mul_comm]
theorem headerPlan_eq_formulaHeader (table : GraphTables.Table) (tail head row : Nat) (ambient : Ambient) : headerPlan.flatMap (Emitter.commandBits (values table.vertices table.darts tail head row) ambient) = formulaHeader table := headerPlan_bits table.vertices table.darts tail head row ambient
theorem outputStream_eq_clauseBits (table : GraphTables.Table) : outputStream rowPlan table (List.finRange table.darts) = encodeWords ((FinalTableFormula.output table).clauses.flatMap Complexity.clauseWords) := by calc _ = (List.finRange table.darts).flatMap (fun e => encodeWords ((VerifierToCNF.eventBlock (FinalCNFPattern.tableVerifier table) (by decide) e).flatMap Complexity.clauseWords)) := by apply List.flatMap_congr intro e he exact rowPlan_bits table e _ = encodeWords ((List.finRange table.darts).flatMap (fun e => (VerifierToCNF.eventBlock (FinalCNFPattern.tableVerifier table) (by decide) e).flatMap Complexity.clauseWords)) := (encodeWords_flatMap _ _).symm _ = _ := by congr 1 rw [← List.flatMap_assoc] rfl
theorem header_append_outputStream (table : GraphTables.Table) : formulaHeader table ++ outputStream rowPlan table (List.finRange table.darts) = formulaBits (FinalTableFormula.output table) := by rw [formulaHeader_eq, outputStream_eq_clauseBits] exact (encodeWords_append _ _).symm
theorem emitted_output_eq (table : GraphTables.Table) (tail head row : Nat) (ambient : Ambient) : headerPlan.flatMap (Emitter.commandBits (values table.vertices table.darts tail head row) ambient) ++ outputStream rowPlan table (List.finRange table.darts) = formulaBits (FinalTableFormula.output table) := by rw [headerPlan_eq_formulaHeader] exact header_append_outputStream table
theorem reversed_accumulator_output (table : GraphTables.Table) : (formulaHeader table ++ outputStream rowPlan table (List.finRange table.darts)).reverse.reverse = formulaBits (FinalTableFormula.output table) := by rw [List.reverse_reverse, header_append_outputStream]
theorem accumulator_length_bound (table : GraphTables.Table) : (formulaHeader table ++ outputStream rowPlan table (List.finRange table.darts)).reverse.length ≤ FinalTableFormula.sizePolynomial.eval (GraphTables.tableBits table).length := by rw [List.length_reverse, header_append_outputStream] exact FinalTableFormula.formulaBits_length_le_polynomial table
open PCP
noncomputable def rowTimePolynomial : Polynomial Nat := Polynomial.C 860160 * (Polynomial.C 3 * (Polynomial.X + Polynomial.C 1) + Polynomial.C 3) + Polynomial.C 12 * Polynomial.X + Polynomial.C 15
theorem rowTimePolynomial_eval (N : Nat) : rowTimePolynomial.eval N = rowTime rowPlan N := by simp only [rowTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, rowTime, rowPlan_length]
theorem rowTime_expanded (N : Nat) : rowTime rowPlan N = 2580492 * N + 5160975 := by rw [rowTime, rowPlan_length] omega
noncomputable def phaseTimePolynomial : Polynomial Nat := headerTimePolynomial + (Polynomial.X * (rowTimePolynomial + Polynomial.C 1) + Polynomial.C 1) + (FinalTableFormula.sizePolynomial + Polynomial.C 1)
theorem phaseTimePolynomial_eval (N : Nat) : phaseTimePolynomial.eval N = headerTimePolynomial.eval N + (N * (rowTime rowPlan N + 1) + 1) + (FinalTableFormula.sizePolynomial.eval N + 1) := by simp only [phaseTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, rowTimePolynomial_eval]
theorem phaseTimePolynomial_eval_expanded (N : Nat) : phaseTimePolynomial.eval N = 4532428812 * N ^ 2 + 5484585 * N + 56 := by rw [phaseTimePolynomial_eval, headerTimePolynomial_eval, rowTime_expanded, FinalTableFormula.sizePolynomial_eval] ring
theorem phaseTime_le {N rows outputLength : Nat} (rowBound : rows ≤ N) (outputBound : outputLength ≤ FinalTableFormula.sizePolynomial.eval N) : headerTimePolynomial.eval N + (rows * (rowTime rowPlan N + 1) + 1) + (outputLength + 1) ≤ phaseTimePolynomial.eval N := by have hrows := Nat.mul_le_mul_right (rowTime rowPlan N + 1) rowBound rw [phaseTimePolynomial_eval] omega
theorem table_phaseTime_le (table : GraphTables.Table) : headerTimePolynomial.eval (GraphTables.tableBits table).length + (table.darts * (rowTime rowPlan (GraphTables.tableBits table).length + 1) + 1) + ((formulaBits (FinalTableFormula.output table)).length + 1) ≤ phaseTimePolynomial.eval (GraphTables.tableBits table).length := phaseTime_le (GraphTables.darts_le_tableBits_length table) (FinalTableFormula.formulaBits_length_le_polynomial table)
noncomputable def finalTimePolynomial (C : Nat) : Polynomial Nat := phaseTimePolynomial + Polynomial.C 12 * (Polynomial.X + phaseTimePolynomial * Polynomial.C C + Polynomial.C 1) + Polynomial.C 1
theorem finalTimePolynomial_eval (C N : Nat) : (finalTimePolynomial C).eval N = phaseTimePolynomial.eval N + 12 * (N + phaseTimePolynomial.eval N * C + 1) + 1 := by simp only [finalTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X]
theorem finalTime_le (C N workLength : Nat) (workBound : workLength ≤ N + phaseTimePolynomial.eval N * C) : phaseTimePolynomial.eval N + 12 * (workLength + 1) + 1 ≤ (finalTimePolynomial C).eval N := by have h := Nat.mul_le_mul_left 12 (Nat.add_le_add_right workBound 1) rw [finalTimePolynomial_eval] omega
end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
namespace MinUncutGames.Foundations.Complexity.FinalCNFCleanup
open Turing MachineCompositionopen FinalCNFMachine (State)open FinalCNFMachine.Program (Tape Plan)
section Redirect
variable {K Λ Λ' σ : Type} {Γ : K → Type} [DecidableEq K]
def redirectLabel (labels : Λ → Λ') (haltTarget : Option Λ') : Option Λ → Option Λ' | none => haltTarget | some label => some (labels label)
def redirectCfg (labels : Λ → Λ') (haltTarget : Option Λ') (cfg : TM2.Cfg Γ Λ σ) : TM2.Cfg Γ Λ' σ := ⟨redirectLabel labels haltTarget cfg.l, cfg.var, cfg.stk⟩
def redirectStmt (labels : Λ → Λ') (haltTarget : Option Λ') : TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ' σ | .push k f next => .push k f (redirectStmt labels haltTarget next) | .peek k f next => .peek k f (redirectStmt labels haltTarget next) | .pop k f next => .pop k f (redirectStmt labels haltTarget next) | .load f next => .load f (redirectStmt labels haltTarget next) | .branch test yes no => .branch test (redirectStmt labels haltTarget yes) (redirectStmt labels haltTarget no) | .goto label => .goto (fun state => labels (label state)) | .halt => match haltTarget with | none => .halt | some label => .goto (fun _ => label)
theorem stepAux_redirect (labels : Λ → Λ') (haltTarget : Option Λ') (stmt : TM2.Stmt Γ Λ σ) (state : σ) (tapes : ∀ k, List (Γ k)) : TM2.stepAux (redirectStmt labels haltTarget stmt) state tapes = redirectCfg labels haltTarget (TM2.stepAux stmt state tapes) := by induction stmt generalizing state tapes with | push k f next ih => exact ih state (Function.update tapes k (f state :: tapes k)) | peek k f next ih => exact ih (f state (tapes k).head?) tapes | pop k f next ih => exact ih (f state (tapes k).head?) (Function.update tapes k (tapes k).tail) | load f next ih => exact ih (f state) tapes | branch test yes no ihYes ihNo => cases h : test state with | false => simpa only [redirectStmt, TM2.stepAux, h, Bool.cond_false] using ihNo state tapes | true => simpa only [redirectStmt, TM2.stepAux, h, Bool.cond_true] using ihYes state tapes | goto label => rfl | halt => cases haltTarget <;> rfl
end Redirect
def chosen : List Tape := [.input, .accumulator, .scratch, .vertices, .darts, .tail, .head, .rowIndex, .archive, .reverseIndex, .scanWork, .indexWork]
@[simp] theorem chosen_length : chosen.length = 12 := rfl
@[simp] theorem mem_chosen (tape : Tape) : tape ∈ chosen ↔ tape ≠ .output := by cases tape <;> simp [chosen]
abbrev Label (headerPlan rowPlan : Plan) := FinalCNFMachine.Program.Label headerPlan.length rowPlan.length ⊕ (MachineDrainMany.Label chosen ⊕ Unit)
def cleanupLabel (headerPlan rowPlan : Plan) : MachineDrainMany.Label chosen → Label headerPlan rowPlan := fun label => .inr (.inl label)
def resetLabel (headerPlan rowPlan : Plan) : Label headerPlan rowPlan := .inr (.inr ())
def cleanupEntry (headerPlan rowPlan : Plan) : Option (Label headerPlan rowPlan) := MachineDrainMany.entry chosen (cleanupLabel headerPlan rowPlan) (some (resetLabel headerPlan rowPlan))
def completedProgram (headerPlan rowPlan : Plan) : Label headerPlan rowPlan → TM2.Stmt (fun _ : Tape => Bool) (Label headerPlan rowPlan) (State Unit) | .inl label => redirectStmt Sum.inl (cleanupEntry headerPlan rowPlan) (FinalCNFMachine.Program.program headerPlan rowPlan label) | .inr (.inl label) => MachineDrainMany.instruction chosen (cleanupLabel headerPlan rowPlan) (some (resetLabel headerPlan rowPlan)) label | .inr (.inr _) => .load (fun _ => (FinalCNFMachine.Program.machine headerPlan rowPlan).initialState) .halt
def completedMachine (headerPlan rowPlan : Plan) : FinTM2 where K := Tape k₀ := .input k₁ := .output Γ _ := Bool Λ := Label headerPlan rowPlan main := .inl .copyFirst σ := State Unit initialState := (FinalCNFMachine.Program.machine headerPlan rowPlan).initialState m := completedProgram headerPlan rowPlan
def embeddedCfg (headerPlan rowPlan : Plan) (cfg : (FinalCNFMachine.Program.machine headerPlan rowPlan).Cfg) : (completedMachine headerPlan rowPlan).Cfg := redirectCfg Sum.inl (cleanupEntry headerPlan rowPlan) cfg
theorem step_simulation (headerPlan rowPlan : Plan) (a b : (FinalCNFMachine.Program.machine headerPlan rowPlan).Cfg) (step : (FinalCNFMachine.Program.machine headerPlan rowPlan).step a = some b) : (completedMachine headerPlan rowPlan).step (embeddedCfg headerPlan rowPlan a) = some (embeddedCfg headerPlan rowPlan b) := by cases a with | mk label state tapes => cases label with | none => simp [FinTM2.step, TM2.step] at step | some label => have hb : TM2.stepAux (FinalCNFMachine.Program.program headerPlan rowPlan label) state tapes = b := Option.some.inj step rw [← hb] change some (TM2.stepAux (redirectStmt Sum.inl (cleanupEntry headerPlan rowPlan) (FinalCNFMachine.Program.program headerPlan rowPlan label)) state tapes) = _ erw [stepAux_redirect] rfl
@[simp] theorem embedded_init (headerPlan rowPlan : Plan) (input : List Bool) : embeddedCfg headerPlan rowPlan (initList (FinalCNFMachine.Program.machine headerPlan rowPlan) input) = initList (completedMachine headerPlan rowPlan) input := rfl
theorem finalTapes_eq (base : Tape → List Bool) : MachineDrainMany.finalTapes chosen base = MachineDrainMany.haltTapes .output (base .output) := by funext tape rw [MachineDrainMany.finalTapes_apply] simp only [mem_chosen] by_cases h : tape = .output · subst tape simp [MachineDrainMany.haltTapes] · simp [MachineDrainMany.haltTapes, h]
theorem haltList_eq (headerPlan rowPlan : Plan) (output : List Bool) : haltList (completedMachine headerPlan rowPlan) output = ⟨none, (FinalCNFMachine.Program.machine headerPlan rowPlan).initialState, MachineDrainMany.haltTapes .output output⟩ := by congr 1
def cleanupExecution (headerPlan rowPlan : Plan) (state : State Unit) (base : Tape → List Bool) : StateTransition.EvalsToInTime (completedMachine headerPlan rowPlan).step ⟨cleanupEntry headerPlan rowPlan, state, base⟩ (some (haltList (completedMachine headerPlan rowPlan) (base .output))) (MachineDrainMany.steps chosen base + 1) := by let after : (completedMachine headerPlan rowPlan).Cfg := ⟨some (resetLabel headerPlan rowPlan), (state.1, MachineDrainMany.finalRegister chosen state.2), MachineDrainMany.finalTapes chosen base⟩ have drains : StateTransition.EvalsToInTime (completedMachine headerPlan rowPlan).step ⟨cleanupEntry headerPlan rowPlan, state, base⟩ (some after) (MachineDrainMany.steps chosen base) := { steps := MachineDrainMany.steps chosen base evals_in_steps := MachineDrainMany.trace chosen (cleanupLabel headerPlan rowPlan) (some (resetLabel headerPlan rowPlan)) (completedProgram headerPlan rowPlan) (fun _ => rfl) base state.1 state.2 steps_le_m := le_rfl } have reset : StateTransition.EvalsToInTime (completedMachine headerPlan rowPlan).step after (some (haltList (completedMachine headerPlan rowPlan) (base .output))) 1 := { steps := 1 evals_in_steps := by change some (⟨none, (FinalCNFMachine.Program.machine headerPlan rowPlan).initialState, MachineDrainMany.finalTapes chosen base⟩ : (completedMachine headerPlan rowPlan).Cfg) = some (haltList (completedMachine headerPlan rowPlan) (base .output)) erw [finalTapes_eq, haltList_eq] rfl steps_le_m := le_rfl } simpa only [Nat.add_comm] using StateTransition.EvalsToInTime.trans _ (MachineDrainMany.steps chosen base) 1 _ after _ drains reset
def outputsInTime (headerPlan rowPlan : Plan) (input output : List Bool) (state : State Unit) (base : Tape → List Bool) (budget : Nat) (raw : StateTransition.EvalsToInTime (FinalCNFMachine.Program.machine headerPlan rowPlan).step (initList (FinalCNFMachine.Program.machine headerPlan rowPlan) input) (some ⟨none, state, base⟩) budget) (correctOutput : base .output = output) : TM2OutputsInTime (completedMachine headerPlan rowPlan) input (some output) (budget + 12 * (input.length + budget * Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan) + 1) + 1) := by let lifted := liftExecutionInTime (FinalCNFMachine.Program.machine headerPlan rowPlan).step (completedMachine headerPlan rowPlan).step (embeddedCfg headerPlan rowPlan) (step_simulation headerPlan rowPlan) raw have joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ lifted (cleanupExecution headerPlan rowPlan state base) have stackBound : ∀ tape, (base tape).length ≤ input.length + budget * Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan) := by intro tape have h := Runtime.executionSizeBound (FinalCNFMachine.Program.machine headerPlan rowPlan).step (fun cfg => (cfg.stk tape).length) (Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan)) (Runtime.stepStackLength (FinalCNFMachine.Program.machine headerPlan rowPlan) tape) raw exact h.trans (Nat.add_le_add_right (Runtime.initialStackLength (FinalCNFMachine.Program.machine headerPlan rowPlan) input tape) _) have cleanupBound := MachineDrainMany.steps_le_uniform chosen base _ stackBound rw [chosen_length] at cleanupBound rw [embedded_init, correctOutput] at joined exact { toEvalsTo := joined.toEvalsTo steps_le_m := joined.steps_le_m.trans (by omega) }
noncomputable def completedTime (headerPlan rowPlan : Plan) (rawTime : Polynomial Nat) : Polynomial Nat := rawTime + Polynomial.C 12 * (Polynomial.X + rawTime * Polynomial.C (Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan)) + 1) + 1
theorem completedTime_eval (headerPlan rowPlan : Plan) (rawTime : Polynomial Nat) (n : Nat) : (completedTime headerPlan rowPlan rawTime).eval n = rawTime.eval n + 12 * (n + rawTime.eval n * Runtime.programPushBound (FinalCNFMachine.Program.machine headerPlan rowPlan) + 1) + 1 := by simp [completedTime]
end MinUncutGames.Foundations.Complexity.FinalCNFCleanup
namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
open Turing PCP
theorem emittedBytes_eq_formulaBits (table : GraphTables.Table) : emittedBytes rowPlan table = formulaBits (FinalTableFormula.output table) := header_append_outputStream table
theorem rawBudget_le_phaseTime (table : GraphTables.Table) : rawBudget rowPlan table ≤ phaseTimePolynomial.eval (GraphTables.tableBits table).length := by unfold rawBudget rw [emittedBytes_eq_formulaBits] simpa only [Nat.add_assoc] using table_phaseTime_le table
noncomputable def computableInPolyTime : TM2ComputableInPolyTime GraphTables.tableBits formulaBits FinalTableFormula.output where tm := FinalCNFCleanup.completedMachine headerPlan rowPlan inputAlphabet := Equiv.refl Bool outputAlphabet := Equiv.refl Bool time := finalTimePolynomial (Runtime.programPushBound (machine headerPlan rowPlan)) outputsFun table := by change TM2OutputsInTime (FinalCNFCleanup.completedMachine headerPlan rowPlan) ((GraphTables.tableBits table).map id) (some ((formulaBits (FinalTableFormula.output table)).map id)) ((finalTimePolynomial (Runtime.programPushBound (machine headerPlan rowPlan))).eval (GraphTables.tableBits table).length) have input_eq : @List.map ((FinalCNFCleanup.completedMachine headerPlan rowPlan).Γ (FinalCNFCleanup.completedMachine headerPlan rowPlan).k₀) ((FinalCNFCleanup.completedMachine headerPlan rowPlan).Γ (FinalCNFCleanup.completedMachine headerPlan rowPlan).k₀) id (GraphTables.tableBits table) = GraphTables.tableBits table := List.map_id _ have output_eq : @List.map ((FinalCNFCleanup.completedMachine headerPlan rowPlan).Γ (FinalCNFCleanup.completedMachine headerPlan rowPlan).k₁) ((FinalCNFCleanup.completedMachine headerPlan rowPlan).Γ (FinalCNFCleanup.completedMachine headerPlan rowPlan).k₁) id (formulaBits (FinalTableFormula.output table)) = formulaBits (FinalTableFormula.output table) := List.map_id _ rw [input_eq, output_eq, finalTimePolynomial_eval] let raw := rawRun rowPlan table let bounded : StateTransition.EvalsToInTime (machine headerPlan rowPlan).step (initList (machine headerPlan rowPlan) (GraphTables.tableBits table)) (some ⟨none, ((raw.finalAmbient, ()), none), raw.finalTapes⟩) (phaseTimePolynomial.eval (GraphTables.tableBits table).length) := { toEvalsTo := raw.execution.toEvalsTo steps_le_m := raw.execution.steps_le_m.trans (rawBudget_le_phaseTime table) } have correct : raw.finalTapes .output = formulaBits (FinalTableFormula.output table) := raw.output.trans (emittedBytes_eq_formulaBits table) have run := FinalCNFCleanup.outputsInTime headerPlan rowPlan (GraphTables.tableBits table) (formulaBits (FinalTableFormula.output table)) ((raw.finalAmbient, ()), none) raw.finalTapes (phaseTimePolynomial.eval (GraphTables.tableBits table).length) bounded correct exact run
end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import Mathlibimport OAI.Computability.MinUncut.PCP.FinalBooleanVerifier
namespace OAI
sectionnamespace MinUncutGames.Foundations.Complexity.FinalCNFPattern
open PCPopen scoped BigOperators
abbrev Label := FinalBooleanVerifier.Label
abbrev labelEquiv : Label ≃ Fin 64 := AlphabetTable.Enumeration.labelEquiv
theorem labelEquiv_val (label : Label) : (labelEquiv label).val = ∑ i : Fin 6, AlphabetTable.Enumeration.bitValue (label i) * 2 ^ i.val := AlphabetTable.Enumeration.labelEquiv_val label
def labelIndex (label : Label) : Fin 64 := labelEquiv label
def labelBits (index : Fin 64) : Label := labelEquiv.symm index
@[simp] theorem labelBits_labelIndex (label : Label) : labelBits (labelIndex label) = label := labelEquiv.symm_apply_apply label
@[simp] theorem labelIndex_labelBits (index : Fin 64) : labelIndex (labelBits index) = index := labelEquiv.apply_symm_apply index
def leftHalf (bits : VerifierToCNF.Pattern 12) : Label := fun j => bits (Fin.castAdd 6 j)
def rightHalf (bits : VerifierToCNF.Pattern 12) : Label := fun j => bits (Fin.natAdd 6 j)
def relationAddress (bits : VerifierToCNF.Pattern 12) : Fin 4096 := GraphTables.relationIndex (labelIndex (leftHalf bits), labelIndex (rightHalf bits))
theorem relationAddress_val (bits : VerifierToCNF.Pattern 12) : (relationAddress bits).val = 64 * (labelIndex (leftHalf bits)).val + (labelIndex (rightHalf bits)).val := by rw [relationAddress, GraphTables.relationIndex_val, Nat.add_comm]
def patternRelationIndex (p : VerifierToCNF.PatternIndex 12) : Fin 4096 := relationAddress (VerifierToCNF.patternAt 12 p)
@[simp] theorem patternRelationIndex_eq (p : VerifierToCNF.PatternIndex 12) : patternRelationIndex p = relationAddress (VerifierToCNF.patternAt 12 p) := rfl
def tableGraph (table : GraphTables.Table) : ConstraintGraph (Fin table.vertices) (Fin table.darts) Label := (GraphTables.semantics table).reindex (Equiv.refl _) (Equiv.refl _) labelEquiv.symm
@[simp] theorem tableGraph_tail (table : GraphTables.Table) (e : Fin table.darts) : (tableGraph table).tail e = table.rows[e].tail := rfl
@[simp] theorem tableGraph_reverse (table : GraphTables.Table) (e : Fin table.darts) : (tableGraph table).reverse e = table.rows[e].reverseIndex := rfl
@[simp] theorem tableGraph_accepts (table : GraphTables.Table) (e : Fin table.darts) (a b : Label) : (tableGraph table).accepts e a b = GraphTables.relationAt table.rows[e].relation (labelIndex a) (labelIndex b) := rfl
abbrev tableVerifier (table : GraphTables.Table) : VerifierToCNF.FiniteVerifier 12 := FinalBooleanVerifier.verifier (tableGraph table) (Equiv.refl _) (Equiv.refl _)
theorem relation_lookup_eq_verifier_accepts (table : GraphTables.Table) (e : Fin table.darts) (bits : VerifierToCNF.Pattern 12) : table.rows[e].relation[relationAddress bits] = (tableVerifier table).accepts e bits := rfl
theorem pattern_lookup_eq_verifier_accepts (table : GraphTables.Table) (e : Fin table.darts) (p : VerifierToCNF.PatternIndex 12) : table.rows[e].relation[patternRelationIndex p] = (tableVerifier table).accepts e (VerifierToCNF.patternAt 12 p) := rfl
theorem verifier_accepts_eq_lookup (table : GraphTables.Table) (e : Fin table.darts) (bits : VerifierToCNF.Pattern 12) : (tableVerifier table).accepts e bits = table.rows[e].relation[relationAddress bits] := rfl
theorem buffer_lookup_eq_verifier_accepts (table : GraphTables.Table) (e : Fin table.darts) (buffer : Fin 4096 → Bool) (read_correct : ∀ i, buffer i = table.rows[e].relation[i]) (bits : VerifierToCNF.Pattern 12) : buffer (relationAddress bits) = (tableVerifier table).accepts e bits := (read_correct _).trans (relation_lookup_eq_verifier_accepts table e bits)
theorem pattern_buffer_lookup_eq_verifier_accepts (table : GraphTables.Table) (e : Fin table.darts) (buffer : Fin 4096 → Bool) (read_correct : ∀ i, buffer i = table.rows[e].relation[i]) (p : VerifierToCNF.PatternIndex 12) : buffer (patternRelationIndex p) = (tableVerifier table).accepts e (VerifierToCNF.patternAt 12 p) := buffer_lookup_eq_verifier_accepts table e buffer read_correct _
end MinUncutGames.Foundations.Complexity.FinalCNFPattern
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688import Mathlibimport OAI.Computability.MinUncut.Games.FinalCNFHeader
namespace OAI
namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
open PCP PCP.AlphabetTable FinalCNFTableAdapter
def remainingEvents (table : GraphTables.Table) (r : Nat) : List (Fin table.darts) := (List.finRange table.darts).drop r
def processedEvents (table : GraphTables.Table) (r : Nat) : List (Fin table.darts) := (List.finRange table.darts).take r
def inputStream (table : GraphTables.Table) (events : List (Fin table.darts)) : List Bool := events.flatMap (fun e => encodeWords (GraphTables.rowWords table.rows[e]))
def outputStream (plan : Plan) (table : GraphTables.Table) (events : List (Fin table.darts)) : List Bool := events.flatMap (fun e => plan.flatMap (Emitter.commandBits (rowOperands table e) (rowRelation table e)))
@[simp] theorem remainingEvents_zero (table : GraphTables.Table) : remainingEvents table 0 = List.finRange table.darts := by simp [remainingEvents]
@[simp] theorem remainingEvents_length (table : GraphTables.Table) (r : Nat) : (remainingEvents table r).length = table.darts - r := by simp [remainingEvents]
@[simp] theorem remainingEvents_done (table : GraphTables.Table) : remainingEvents table table.darts = [] := by simp [remainingEvents]
theorem remainingEvents_cons (table : GraphTables.Table) (r : Nat) (h : r < table.darts) : remainingEvents table r = ⟨r, h⟩ :: remainingEvents table (r + 1) := by unfold remainingEvents rw [List.drop_eq_getElem_cons (l := List.finRange table.darts) (i := r) (by simpa using h)] simp
@[simp] theorem processedEvents_zero (table : GraphTables.Table) : processedEvents table 0 = [] := by simp [processedEvents]
@[simp] theorem processedEvents_done (table : GraphTables.Table) : processedEvents table table.darts = List.finRange table.darts := by simp [processedEvents]
theorem processedEvents_succ (table : GraphTables.Table) (r : Nat) (h : r < table.darts) : processedEvents table (r + 1) = processedEvents table r ++ [⟨r, h⟩] := by unfold processedEvents rw [List.take_succ_eq_append_getElem (l := List.finRange table.darts) (i := r) (by simpa using h)] simp
theorem processed_append_remaining (table : GraphTables.Table) (r : Nat) : processedEvents table r ++ remainingEvents table r = List.finRange table.darts := by exact List.take_append_drop r (List.finRange table.darts)
@[simp] theorem inputStream_nil (table : GraphTables.Table) : inputStream table [] = [] := rfl
@[simp] theorem inputStream_cons (table : GraphTables.Table) (e : Fin table.darts) (events : List (Fin table.darts)) : inputStream table (e :: events) = encodeWords (GraphTables.rowWords table.rows[e]) ++ inputStream table events := rfl
@[simp] theorem inputStream_append (table : GraphTables.Table) (first rest : List (Fin table.darts)) : inputStream table (first ++ rest) = inputStream table first ++ inputStream table rest := by simp only [inputStream, List.flatMap_append]
@[simp] theorem outputStream_nil (plan : Plan) (table : GraphTables.Table) : outputStream plan table [] = [] := rfl
@[simp] theorem outputStream_cons (plan : Plan) (table : GraphTables.Table) (e : Fin table.darts) (events : List (Fin table.darts)) : outputStream plan table (e :: events) = plan.flatMap (Emitter.commandBits (rowOperands table e) (rowRelation table e)) ++ outputStream plan table events := rfl
@[simp] theorem outputStream_append (plan : Plan) (table : GraphTables.Table) (first rest : List (Fin table.darts)) : outputStream plan table (first ++ rest) = outputStream plan table first ++ outputStream plan table rest := by simp only [outputStream, List.flatMap_append]
theorem inputStream_remaining_cons (table : GraphTables.Table) (r : Nat) (h : r < table.darts) : inputStream table (remainingEvents table r) = encodeWords (GraphTables.rowWords table.rows[(⟨r, h⟩ : Fin table.darts)]) ++ inputStream table (remainingEvents table (r + 1)) := by rw [remainingEvents_cons table r h, inputStream_cons]
theorem outputStream_remaining_cons (plan : Plan) (table : GraphTables.Table) (r : Nat) (h : r < table.darts) : outputStream plan table (remainingEvents table r) = plan.flatMap (Emitter.commandBits (rowOperands table ⟨r, h⟩) (rowRelation table ⟨r, h⟩)) ++ outputStream plan table (remainingEvents table (r + 1)) := by rw [remainingEvents_cons table r h, outputStream_cons]
theorem outputStream_processed_succ (plan : Plan) (table : GraphTables.Table) (r : Nat) (h : r < table.darts) : outputStream plan table (processedEvents table (r + 1)) = outputStream plan table (processedEvents table r) ++ plan.flatMap (Emitter.commandBits (rowOperands table ⟨r, h⟩) (rowRelation table ⟨r, h⟩)) := by rw [processedEvents_succ table r h, outputStream_append] simp
theorem inputStream_split (table : GraphTables.Table) (r : Nat) : inputStream table (List.finRange table.darts) = inputStream table (processedEvents table r) ++ inputStream table (remainingEvents table r) := by rw [← inputStream_append, processed_append_remaining]
theorem outputStream_split (plan : Plan) (table : GraphTables.Table) (r : Nat) : outputStream plan table (List.finRange table.darts) = outputStream plan table (processedEvents table r) ++ outputStream plan table (remainingEvents table r) := by rw [← outputStream_append, processed_append_remaining]
private theorem encodeWords_flatMap_rows {α : Type} (rows : List α) (words : α → List Nat) : encodeWords (rows.flatMap words) = rows.flatMap (fun row => encodeWords (words row)) := by induction rows with | nil => rfl | cons row rows ih => simp only [List.flatMap_cons, encodeWords_append, ih]
theorem rowList_eq_finRange_map (table : GraphTables.Table) : GraphTables.rowList table = (List.finRange table.darts).map (fun e => table.rows[e]) := by rw [← List.ofFn_eq_map, ← Vector.toList_ofFn] change table.rows.toList = (Vector.ofFn (fun i => table.rows[i.val])).toList rw [Vector.ofFn_getElem]
theorem inputStream_all (table : GraphTables.Table) : inputStream table (List.finRange table.darts) = tableRowsBits (genericTable table) := by rw [tableRowsBits, genericTable_rowList] change inputStream table (List.finRange table.darts) = encodeWords (((GraphTables.rowList table).map genericRow).flatMap (fun row : GenericGraphTables.DartRow 64 table.vertices table.darts => GenericGraphTables.rowWords row)) rw [List.flatMap_map] simp only [genericRow_words] rw [rowList_eq_finRange_map, List.flatMap_map, encodeWords_flatMap_rows] rfl
theorem inputStream_remaining_zero (table : GraphTables.Table) : inputStream table (remainingEvents table 0) = tableRowsBits (genericTable table) := by rw [remainingEvents_zero, inputStream_all]
theorem outputStream_accumulator_succ (plan : Plan) (table : GraphTables.Table) (r : Nat) (h : r < table.darts) (header : List Bool) : (plan.flatMap (Emitter.commandBits (rowOperands table ⟨r, h⟩) (rowRelation table ⟨r, h⟩))).reverse ++ (header ++ outputStream plan table (processedEvents table r)).reverse = (header ++ outputStream plan table (processedEvents table (r + 1))).reverse := by rw [outputStream_processed_succ plan table r h] simp only [List.reverse_append, List.append_assoc]
open Turing PCP PCP.AlphabetTable
structure LoopInvariant (table : GraphTables.Table) (r : Nat) (base : Tape → List Bool) : Prop where input : base .input = inputStream table (remainingEvents table r) archive : base .archive = GraphTables.tableBits table vertices : base .vertices = encodeWord table.vertices darts : base .darts = encodeWord table.darts index : base .rowIndex = encodeWord r tail : base .tail = [] head : base .head = [] reverse : base .reverseIndex = [] scratch : base .scratch = []
structure LoopRun (headerPlan plan : Plan) (table : GraphTables.Table) (r remaining : Nat) (base : Tape → List Bool) (ambient : Ambient) where finalAmbient : Ambient finalTapes : Tape → List Bool execution : StateTransition.EvalsToInTime (TM2.step (program headerPlan plan)) ⟨some .guard, ((ambient, ()), none), base⟩ (some ⟨some .reverseOutput, ((finalAmbient, ()), none), finalTapes⟩) (remaining * (rowTime plan (GraphTables.tableBits table).length + 1) + 1) accumulator : finalTapes .accumulator = (outputStream plan table (remainingEvents table r)).reverse ++ base .accumulator output : finalTapes .output = base .output
theorem rowInvariant_succ (plan : Plan) (table : GraphTables.Table) (r : Nat) (hr : r < table.darts) (base : Tape → List Bool) (invariant : LoopInvariant table r base) : LoopInvariant table (r + 1) (rowResultTapes plan base table ⟨r, hr⟩ (inputStream table (remainingEvents table (r + 1)))) := by constructor · exact rowResult_input _ _ _ _ _ · exact (rowResult_frame _ _ _ _ _ .archive (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)).trans invariant.archive · exact (rowResult_frame _ _ _ _ _ .vertices (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)).trans invariant.vertices · exact (rowResult_frame _ _ _ _ _ .darts (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)).trans invariant.darts · exact rowResult_index _ _ _ _ _ · exact rowResult_tail _ _ _ _ _ · exact rowResult_head _ _ _ _ _ · exact rowResult_reverse _ _ _ _ _ · exact (rowResult_frame _ _ _ _ _ .scratch (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)).trans invariant.scratch
theorem rowWords_nonempty (table : GraphTables.Table) (e : Fin table.darts) : encodeWords (GraphTables.rowWords table.rows[e]) ≠ [] := by simp [GraphTables.rowWords, encodeWords, encodeWord]
noncomputable def loopInTime (headerPlan plan : Plan) (table : GraphTables.Table) (remaining : Nat) : ∀ (r : Nat) (_ : r + remaining = table.darts) (base : Tape → List Bool) (ambient : Ambient), LoopInvariant table r base → LoopRun headerPlan plan table r remaining base ambient := by induction remaining with | zero => intro r hcount base ambient invariant have hr : r = table.darts := by omega have hinput : base .input = [] := by simpa only [hr, remainingEvents_done, inputStream_nil] using invariant.input refine { finalAmbient := ambient finalTapes := base execution := ?_ accumulator := ?_ output := rfl } · simpa only [Nat.zero_mul, Nat.zero_add] using guardEndInTime headerPlan plan base ambient hinput · simp only [hr, remainingEvents_done, outputStream_nil, List.reverse_nil, List.nil_append] | succ remaining ih => intro r hcount base ambient invariant have hr : r < table.darts := by omega let e : Fin table.darts := ⟨r, hr⟩ let rest := inputStream table (remainingEvents table (r + 1)) let next := rowResultTapes plan base table e rest have hinput : base .input = encodeWords (GraphTables.rowWords table.rows[e]) ++ rest := by rw [invariant.input, inputStream_remaining_cons table r hr] have hnonempty : base .input ≠ [] := by rw [hinput] exact List.append_ne_nil_of_left_ne_nil (rowWords_nonempty table e) rest let guardRun := guardRowInTime headerPlan plan base ambient hnonempty let rowRun := rowInTime headerPlan plan base table e rest hinput invariant.archive invariant.vertices invariant.darts invariant.index invariant.tail invariant.head invariant.reverse invariant.scratch ambient let first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ guardRun rowRun let later := ih (r + 1) (by omega) next (rowRelation table e) (rowInvariant_succ plan table r hr base invariant) let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first later.execution refine { finalAmbient := later.finalAmbient finalTapes := later.finalTapes execution := { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } accumulator := ?_ output := ?_ } · have hb := run.steps_le_m rw [Nat.succ_mul] omega · rw [later.accumulator, outputStream_remaining_cons plan table r hr] simp only [next, rowResult_accumulator, List.reverse_append, List.append_assoc] rfl · rw [later.output] exact rowResult_frame _ _ _ _ _ .output (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) (by decide)
open Turing PCP PCP.AlphabetTable FinalCNFTableAdapter
def emittedBytes (plan : Plan) (table : GraphTables.Table) : List Bool := encodeWords [6 * table.vertices + 36864 * table.darts, 40960 * table.darts] ++ outputStream plan table (List.finRange table.darts)
noncomputable def rawBudget (plan : Plan) (table : GraphTables.Table) : Nat := headerTimePolynomial.eval (GraphTables.tableBits table).length + table.darts * (rowTime plan (GraphTables.tableBits table).length + 1) + 1 + (emittedBytes plan table).length + 1
structure RawRun (plan : Plan) (table : GraphTables.Table) where finalAmbient : Ambient finalTapes : Tape → List Bool execution : StateTransition.EvalsToInTime (machine headerPlan plan).step (initList (machine headerPlan plan) (GraphTables.tableBits table)) (some ⟨none, ((finalAmbient, ()), none), finalTapes⟩) (rawBudget plan table) output : finalTapes .output = emittedBytes plan table
theorem header_loopInvariant (_ : Plan) (table : GraphTables.Table) : LoopInvariant table 0 (headerResultTapes table.vertices table.darts (tableRowsBits (genericTable table))) := by constructor · rw [headerResultTapes_input, inputStream_remaining_zero] · rw [headerResultTapes_archive] exact (tableBits_header_rows (genericTable table)).symm.trans (genericTable_tableBits table) · rfl · rfl · exact headerResultTapes_rowIndex _ _ _ · rfl · rfl · rfl · rfl
noncomputable def rawRun (plan : Plan) (table : GraphTables.Table) : RawRun plan table := by let base := headerResultTapes table.vertices table.darts (tableRowsBits (genericTable table)) let ambient : Ambient := ((), fun _ => false) have headerRun : StateTransition.EvalsToInTime (machine headerPlan plan).step (initList (machine headerPlan plan) (GraphTables.tableBits table)) (some ⟨some .guard, ((ambient, ()), none), base⟩) (headerTimePolynomial.eval (GraphTables.tableBits table).length) := by simpa only [genericTable_tableBits, genericTable_vertices, genericTable_darts, base, ambient] using initializedTableHeaderInTime plan (genericTable table) let loop := loopInTime headerPlan plan table table.darts 0 (by omega) base ambient (header_loopInvariant plan table) have acc : loop.finalTapes .accumulator = (emittedBytes plan table).reverse := by rw [loop.accumulator] simp only [remainingEvents_zero, base, headerResultTapes_accumulator, emittedBytes, List.reverse_append] have out : loop.finalTapes .output = [] := by rw [loop.output] rfl let finalTapes := Reduction.MachineTransfer.tapesAt Tape.accumulator Tape.output loop.finalTapes [] (emittedBytes plan table) have finish : StateTransition.EvalsToInTime (machine headerPlan plan).step ⟨some .reverseOutput, ((loop.finalAmbient, ()), none), loop.finalTapes⟩ (some ⟨none, ((loop.finalAmbient, ()), none), finalTapes⟩) ((emittedBytes plan table).length + 1) := by have run := Reduction.MachineTransfer.transferAtInTime Tape.accumulator Tape.output (by decide) id false .reverseOutput none (program headerPlan plan) rfl loop.finalTapes (loop.finalAmbient, ()) none simpa only [acc, out, List.reverse_reverse, List.length_reverse, List.map_id, List.append_nil, finalTapes, machine, FinTM2.step] using! run let first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ headerRun loop.execution let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first finish exact { finalAmbient := loop.finalAmbient finalTapes := finalTapes execution := { toEvalsTo := run.toEvalsTo steps_le_m := by have hb := run.steps_le_m unfold rawBudget omega } output := by simp [finalTapes, Reduction.MachineTransfer.tapesAt] }
end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
namespace MinUncutGames.Foundations.Complexity.FinalCNFTemplate
open Target PCP
inductive Reference where | query : Fin 12 → Reference | auxiliary : Fin 9 → Reference deriving DecidableEq
structure LiteralTemplate where reference : Reference positive : Bool deriving DecidableEq
abbrev ClauseTemplate := Vector LiteralTemplate 3
def queryLiteral (bits : Fin 12 → Bool) (i : Fin 12) : LiteralTemplate := ⟨.query i, !(bits i)⟩
def auxiliaryLiteral (j : Fin 9) (positive : Bool) : LiteralTemplate := ⟨.auxiliary j, positive⟩
def tautologyTemplate : ClauseTemplate := #v[⟨.query 0, true⟩, ⟨.query 0, false⟩, ⟨.query 0, true⟩]
def chainTemplates (bits : Fin 12 → Bool) : Vector ClauseTemplate 10 := #v[ #v[queryLiteral bits 0, queryLiteral bits 1, auxiliaryLiteral 0 true], #v[auxiliaryLiteral 0 false, queryLiteral bits 2, auxiliaryLiteral 1 true], #v[auxiliaryLiteral 1 false, queryLiteral bits 3, auxiliaryLiteral 2 true], #v[auxiliaryLiteral 2 false, queryLiteral bits 4, auxiliaryLiteral 3 true], #v[auxiliaryLiteral 3 false, queryLiteral bits 5, auxiliaryLiteral 4 true], #v[auxiliaryLiteral 4 false, queryLiteral bits 6, auxiliaryLiteral 5 true], #v[auxiliaryLiteral 5 false, queryLiteral bits 7, auxiliaryLiteral 6 true], #v[auxiliaryLiteral 6 false, queryLiteral bits 8, auxiliaryLiteral 7 true], #v[auxiliaryLiteral 7 false, queryLiteral bits 9, auxiliaryLiteral 8 true], #v[auxiliaryLiteral 8 false, queryLiteral bits 10, queryLiteral bits 11]]
def blockTemplates (accepted : Bool) (bits : Fin 12 → Bool) : Vector ClauseTemplate 10 := if accepted then Vector.replicate 10 tautologyTemplate else chainTemplates bits
def templates (accepted : Bool) (bits : Fin 12 → Bool) : List ClauseTemplate := (blockTemplates accepted bits).toList
def literalAt (accepted : Bool) (bits : Fin 12 → Bool) (clause : Fin 10) (slot : Fin 3) : LiteralTemplate := (blockTemplates accepted bits)[clause][slot]
@[simp] theorem templates_length (accepted : Bool) (bits : Fin 12 → Bool) : (templates accepted bits).length = 10 := Vector.length_toList
theorem templates_true (bits : Fin 12 → Bool) : templates true bits = List.replicate 10 tautologyTemplate := by rfl
theorem templates_false (bits : Fin 12 → Bool) : templates false bits = (chainTemplates bits).toList := by rfl
def literalTemplates (accepted : Bool) (bits : Fin 12 → Bool) : List LiteralTemplate := (templates accepted bits).flatMap fun c => [(c)[0], (c)[1], (c)[2]]
theorem literalTemplates_length (accepted : Bool) (bits : Fin 12 → Bool) : (literalTemplates accepted bits).length = 30 := by unfold literalTemplates rw [VerifierToCNF.length_flatMap_constant _ _ 3 (by intro c hc; rfl), templates_length]
def literalWords (index : Reference → Nat) (literal : LiteralTemplate) : List Nat := [index literal.reference, if literal.positive then 1 else 0]
def clauseWords (index : Reference → Nat) (clause : ClauseTemplate) : List Nat := literalWords index clause[0] ++ literalWords index clause[1] ++ literalWords index clause[2]
def words (accepted : Bool) (bits : Fin 12 → Bool) (index : Reference → Nat) : List Nat := (templates accepted bits).flatMap (clauseWords index)
theorem words_length (accepted : Bool) (bits : Fin 12 → Bool) (index : Reference → Nat) : (words accepted bits index).length = 60 := by unfold words rw [VerifierToCNF.length_flatMap_constant _ _ 6 (by intro c hc; simp [clauseWords, literalWords]), templates_length]
variable (V : VerifierToCNF.FiniteVerifier 12) (e : Fin V.events) (p : VerifierToCNF.PatternIndex 12)
def resolve : Reference → Fin (VerifierToCNF.outputVariables V) | .query i => VerifierToCNF.oldIndex V (V.query e i) | .auxiliary j => VerifierToCNF.freshIndex V e p j
theorem resolve_query_value (i : Fin 12) : (resolve V e p (.query i)).val = (V.query e i).val := by simp only [resolve, VerifierToCNF.oldIndex, Fin.val_castAdd]
theorem resolve_auxiliary_value (j : Fin 9) : (resolve V e p (.auxiliary j)).val = V.«variables» + ((e.val * 4096 + p.val) * 9 + j.val) := by change (VerifierToCNF.freshIndex V e p j).val = _ exact (VerifierToCNF.freshIndex_value V e p j).trans (congrArg (fun k : Nat => V.«variables» + ((e.val * k + p.val) * 9 + j.val)) (show (VerifierToCNF.patterns 12).length = 4096 from VerifierToCNF.patterns_length 12))
def instantiateLiteral (literal : LiteralTemplate) : Literal (VerifierToCNF.outputVariables V) := ⟨resolve V e p literal.reference, literal.positive⟩
def instantiateClause (clause : ClauseTemplate) : Clause (VerifierToCNF.outputVariables V) := #v[instantiateLiteral V e p clause[0], instantiateLiteral V e p clause[1], instantiateLiteral V e p clause[2]]
theorem splitLong_twelve {n : Nat} (ls : Fin 12 → Literal n) (ys : Fin 9 → Fin n) : VerifierToCNF.splitLong (List.ofFn ls) (List.ofFn ys) = [#v[ls 0, ls 1, ⟨ys 0, true⟩], #v[⟨ys 0, false⟩, ls 2, ⟨ys 1, true⟩], #v[⟨ys 1, false⟩, ls 3, ⟨ys 2, true⟩], #v[⟨ys 2, false⟩, ls 4, ⟨ys 3, true⟩], #v[⟨ys 3, false⟩, ls 5, ⟨ys 4, true⟩], #v[⟨ys 4, false⟩, ls 6, ⟨ys 5, true⟩], #v[⟨ys 5, false⟩, ls 7, ⟨ys 6, true⟩], #v[⟨ys 6, false⟩, ls 8, ⟨ys 7, true⟩], #v[⟨ys 7, false⟩, ls 9, ⟨ys 8, true⟩], #v[⟨ys 8, false⟩, ls 10, ls 11]] := by simp only [List.ofFn_succ, List.ofFn_zero, VerifierToCNF.splitLong] rfl
theorem instantiate_templates : (templates (V.accepts e (VerifierToCNF.patternAt 12 p)) (VerifierToCNF.patternAt 12 p)).map (instantiateClause V e p) = VerifierToCNF.block V (by decide) e p := by cases h : V.accepts e (VerifierToCNF.patternAt 12 p) with | false => simp only [h, templates_false, VerifierToCNF.block, Bool.false_eq_true, ↓reduceIte, VerifierToCNF.forbiddenClause, VerifierToCNF.auxiliaryNames] rw [splitLong_twelve] rfl | true => simp only [h, templates_true, VerifierToCNF.block, ↓reduceIte, List.map_replicate] rfl
theorem instantiate_templates_of_acceptance (accepted : Bool) (h : V.accepts e (VerifierToCNF.patternAt 12 p) = accepted) : (templates accepted (VerifierToCNF.patternAt 12 p)).map (instantiateClause V e p) = VerifierToCNF.block V (by decide) e p := by rw [← h] exact instantiate_templates V e p
theorem instantiateClause_words (clause : ClauseTemplate) : Complexity.clauseWords (instantiateClause V e p clause) = clauseWords (fun r => (resolve V e p r).val) clause := rfl
theorem words_eq_block : words (V.accepts e (VerifierToCNF.patternAt 12 p)) (VerifierToCNF.patternAt 12 p) (fun r => (resolve V e p r).val) = (VerifierToCNF.block V (by decide) e p).flatMap Complexity.clauseWords := by rw [← instantiate_templates V e p] simp only [List.flatMap_map, instantiateClause_words] rfl
theorem block_words_length : ((VerifierToCNF.block V (by decide) e p).flatMap Complexity.clauseWords).length = 60 := by rw [← words_eq_block V e p] exact words_length _ _ _
end MinUncutGames.Foundations.Complexity.FinalCNFTemplate
namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
open PCP PCP.AlphabetTable FinalCNFTemplate
def referenceValue (vertices tail head row pattern : Nat) : Reference → Nat | .query i => if i.val < 6 then 6 * tail + i.val else 6 * head + (i.val - 6) | .auxiliary j => 6 * vertices + 36864 * row + (9 * pattern + j.val)
def auxiliaryFlag : Reference → Bool | .query _ => false | .auxiliary _ => true
def tailFlag : Reference → Bool | .query i => decide (i.val < 6) | .auxiliary _ => false
def headFlag : Reference → Bool | .query i => decide (6 ≤ i.val) | .auxiliary _ => false
theorem pattern_lt (p : VerifierToCNF.PatternIndex 12) : p.val < 4096 := by have hlen : (VerifierToCNF.patterns 12).length = 4096 := VerifierToCNF.patterns_length 12 exact lt_of_lt_of_eq p.isLt hlen
def referenceOffset (p : VerifierToCNF.PatternIndex 12) : Reference → Fin 36864 | .query i => ⟨if i.val < 6 then i.val else i.val - 6, by split <;> omega⟩ | .auxiliary j => ⟨9 * p.val + j.val, by have hp := pattern_lt p; omega⟩
def literalPlan (p : VerifierToCNF.PatternIndex 12) (literal : Ambient → LiteralTemplate) : Plan := [.scaledIf 0 6 (fun state => auxiliaryFlag (literal state).reference), .scaledIf 2 6 (fun state => tailFlag (literal state).reference), .scaledIf 3 6 (fun state => headFlag (literal state).reference), .scaledIf 4 36864 (fun state => auxiliaryFlag (literal state).reference), .bounded (fun state => referenceOffset p (literal state).reference), .literal [false], .bit (fun state => (literal state).positive)]
theorem literalPlan_length (p : VerifierToCNF.PatternIndex 12) (literal : Ambient → LiteralTemplate) : (literalPlan p literal).length = 7 := rfl
theorem literalPlan_bits (p : VerifierToCNF.PatternIndex 12) (literal : Ambient → LiteralTemplate) (vertices darts tail head row : Nat) (ambient : Ambient) : (literalPlan p literal).flatMap (Emitter.commandBits (values vertices darts tail head row) ambient) = encodeWords (FinalCNFTemplate.literalWords (referenceValue vertices tail head row p.val) (literal ambient)) := by rcases h : literal ambient with ⟨reference, positive⟩ cases reference with | query i => by_cases hi : i.val < 6 · simp [literalPlan, Emitter.commandBits, h, auxiliaryFlag, tailFlag, headFlag, referenceOffset, referenceValue, FinalCNFTemplate.literalWords, values, hi, show ¬ 6 ≤ i.val by omega, encodeWords, encodeWord, List.replicate_add, List.append_assoc, -List.replicate_append_replicate] rfl · simp [literalPlan, Emitter.commandBits, h, auxiliaryFlag, tailFlag, headFlag, referenceOffset, referenceValue, FinalCNFTemplate.literalWords, values, hi, show 6 ≤ i.val by omega, encodeWords, encodeWord, List.replicate_add, List.append_assoc, -List.replicate_append_replicate] rfl | auxiliary j => simp [literalPlan, Emitter.commandBits, h, auxiliaryFlag, tailFlag, headFlag, referenceOffset, referenceValue, FinalCNFTemplate.literalWords, values, encodeWords, encodeWord, List.replicate_add, List.append_assoc, -List.replicate_append_replicate] rfl
def patternLiteral (p : VerifierToCNF.PatternIndex 12) (clause : Fin 10) (slot : Fin 3) (ambient : Ambient) : LiteralTemplate := literalAt (ambient.2 (FinalCNFPattern.patternRelationIndex p)) (VerifierToCNF.patternAt 12 p) clause slot
def patternPlan (p : VerifierToCNF.PatternIndex 12) : Plan := (List.finRange 10).flatMap fun clause => (List.finRange 3).flatMap fun slot => literalPlan p (patternLiteral p clause slot)
def rowPlan : Plan := (List.finRange (VerifierToCNF.patterns 12).length).flatMap patternPlan
theorem patternPlan_length (p : VerifierToCNF.PatternIndex 12) : (patternPlan p).length = 210 := by unfold patternPlan rw [VerifierToCNF.length_flatMap_constant _ _ 21] · simp · intro clause hclause rw [VerifierToCNF.length_flatMap_constant _ _ 7] · simp · intro slot hslot exact literalPlan_length _ _
theorem rowPlan_length : rowPlan.length = 860160 := by unfold rowPlan rw [VerifierToCNF.length_flatMap_constant _ _ 210] · calc _ = 2 ^ 12 * 210 := by rw [List.length_finRange, VerifierToCNF.patterns_length] _ = 860160 := by decide · intro p hp exact patternPlan_length p
theorem encodeWords_flatMap {α : Type*} (xs : List α) (words : α → List Nat) : encodeWords (xs.flatMap words) = xs.flatMap (fun x => encodeWords (words x)) := by induction xs with | nil => rfl | cons x xs ih => simp only [List.flatMap_cons, encodeWords_append, ih]
theorem patternPlan_bits (p : VerifierToCNF.PatternIndex 12) (vertices darts tail head row : Nat) (ambient : Ambient) : (patternPlan p).flatMap (Emitter.commandBits (values vertices darts tail head row) ambient) = encodeWords (FinalCNFTemplate.words (ambient.2 (FinalCNFPattern.patternRelationIndex p)) (VerifierToCNF.patternAt 12 p) (referenceValue vertices tail head row p.val)) := by unfold patternPlan simp only [List.flatMap_assoc] simp_rw [literalPlan_bits] have hclauses : (List.finRange 10).map (fun c => (blockTemplates (ambient.2 (FinalCNFPattern.patternRelationIndex p)) (VerifierToCNF.patternAt 12 p))[c]) = templates (ambient.2 (FinalCNFPattern.patternRelationIndex p)) (VerifierToCNF.patternAt 12 p) := by rw [← List.ofFn_eq_map] change List.ofFn (fun c : Fin 10 => (blockTemplates (ambient.2 (FinalCNFPattern.patternRelationIndex p)) (VerifierToCNF.patternAt 12 p))[c.val]) = _ rw [← Vector.toList_ofFn, Vector.ofFn_getElem] rfl unfold FinalCNFTemplate.words rw [← hclauses, List.flatMap_map, encodeWords_flatMap] apply List.flatMap_congr intro clause hclause simp only [List.finRange, List.ofFn_succ, List.ofFn_zero, List.flatMap_cons, List.flatMap_nil, patternLiteral, literalAt, FinalCNFTemplate.clauseWords, encodeWords_append, List.append_nil, List.append_assoc] rfl
theorem referenceValue_eq_resolve (table : GraphTables.Table) (e : Fin table.darts) (p : VerifierToCNF.PatternIndex 12) (reference : Reference) : referenceValue table.vertices table.rows[e].tail.val table.rows[table.rows[e].reverseIndex].tail.val e.val p.val reference = (resolve (FinalCNFPattern.tableVerifier table) e p reference).val := by cases reference with | query i => rw [resolve_query_value] refine Fin.addCases (m := 6) (n := 6) (fun j => ?_) (fun j => ?_) i · rw [FinalBooleanVerifier.query_tail] simp only [referenceValue, Fin.val_castAdd, j.isLt, ite_true] change 6 * table.rows[e].tail.val + j.val = j.val + 6 * table.rows[e].tail.val omega · rw [FinalBooleanVerifier.query_head] simp only [referenceValue, Fin.val_natAdd] split · omega · change 6 * table.rows[table.rows[e].reverseIndex].tail.val + (6 + j.val - 6) = j.val + 6 * table.rows[table.rows[e].reverseIndex].tail.val omega | auxiliary j => rw [resolve_auxiliary_value] change 6 * table.vertices + 36864 * e.val + (9 * p.val + j.val) = table.vertices * 6 + ((e.val * 4096 + p.val) * 9 + j.val) omega
theorem rowPlan_bits (table : GraphTables.Table) (e : Fin table.darts) : rowPlan.flatMap (Emitter.commandBits (values table.vertices table.darts table.rows[e].tail.val table.rows[table.rows[e].reverseIndex].tail.val e.val) ((), fun i => table.rows[e].relation[i])) = encodeWords ((VerifierToCNF.eventBlock (FinalCNFPattern.tableVerifier table) (by decide) e).flatMap Complexity.clauseWords) := by unfold rowPlan VerifierToCNF.eventBlock simp only [List.flatMap_assoc] rw [encodeWords_flatMap] apply List.flatMap_congr intro p hp rw [patternPlan_bits] dsimp only rw [FinalCNFPattern.pattern_lookup_eq_verifier_accepts] have href := funext (referenceValue_eq_resolve table e p) rw [href] exact congrArg encodeWords (words_eq_block (FinalCNFPattern.tableVerifier table) e p)
end MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program
end OAI12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import Mathlibimport OAI.Computability.MinUncut.Encoding.ThreeBitTest
namespace OAI
sectionnamespace MinUncutGames.Reduction.FiniteNoise
open scoped BigOperatorsopen MinUncutGames.Foundations.Hastad (noiseWeight)
def realizedBit {D : Nat} (z : Fin D) : Bool := decide (z.val = 0)
def realizedNoise {A : Type*} {D : Nat} (z : A → Fin D) : A → Bool := fun a => realizedBit (z a)
theorem realizedBit_eq_true_iff {D : Nat} (positive : 0 < D) (z : Fin D) : realizedBit z = true ↔ z = ⟨0, positive⟩ := by simp [realizedBit, Fin.ext_iff]
theorem coordinate_fiber_sum {D : Nat} (positive : 0 < D) (b : Bool) : (∑ z : Fin D, if realizedBit z = b then (D : ℝ)⁻¹ else 0) = if b then (D : ℝ)⁻¹ else 1 - (D : ℝ)⁻¹ := by have hd : (D : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt positive have ht : (∑ z : Fin D, if realizedBit z = true then (D : ℝ)⁻¹ else 0) = (D : ℝ)⁻¹ := by simp_rw [realizedBit_eq_true_iff positive] simp have htotal : (∑ z : Fin D, if realizedBit z = false then (D : ℝ)⁻¹ else 0) + (∑ z : Fin D, if realizedBit z = true then (D : ℝ)⁻¹ else 0) = 1 := by rw [← Finset.sum_add_distrib] have he (z : Fin D) : (if realizedBit z = false then (D : ℝ)⁻¹ else 0) + (if realizedBit z = true then (D : ℝ)⁻¹ else 0) = (D : ℝ)⁻¹ := by cases realizedBit z <;> simp simp_rw [he] simp [hd] cases b <;> simp only [Bool.false_eq_true, ite_false, ite_true] · linarith · exact ht
variable {A : Type*} [Fintype A] [DecidableEq A]
theorem noiseWeight_eq_fiber_sum {D : Nat} (positive : 0 < D) (μ : A → Bool) : noiseWeight ((D : ℝ)⁻¹) μ = ∑ z : A → Fin D, ∏ a, if realizedBit (z a) = μ a then (D : ℝ)⁻¹ else 0 := by rw [← Fintype.prod_sum (fun (a : A) (z : Fin D) => if realizedBit z = μ a then (D : ℝ)⁻¹ else 0)] unfold noiseWeight apply Finset.prod_congr rfl intro a _ exact (coordinate_fiber_sum positive (μ a)).symm
omit [DecidableEq A] intheorem fiber_product_eq_indicator {D : Nat} (z : A → Fin D) (μ : A → Bool) : (∏ a, if realizedBit (z a) = μ a then (D : ℝ)⁻¹ else 0) = if realizedNoise z = μ then ((D : ℝ)⁻¹) ^ Fintype.card A else 0 := by classical by_cases h : realizedNoise z = μ · rw [ite_eq_left h] have ha (a : A) : realizedBit (z a) = μ a := congrFun h a simp [ha] · rw [ite_eq_right h] obtain ⟨a, ha⟩ := Function.ne_iff.mp h apply Finset.prod_eq_zero (Finset.mem_univ a) exact ite_eq_right ha
theorem expect_realizedNoise {D : Nat} (positive : 0 < D) (H : (A → Bool) → ℝ) : (𝔼 z : A → Fin D, H (realizedNoise z)) = ∑ μ : A → Bool, noiseWeight ((D : ℝ)⁻¹) μ * H μ := by classical symm simp_rw [noiseWeight_eq_fiber_sum positive, Finset.sum_mul] rw [Finset.sum_comm] simp_rw [fiber_product_eq_indicator] have he (z : A → Fin D) : (∑ μ : A → Bool, (if realizedNoise z = μ then ((D : ℝ)⁻¹) ^ Fintype.card A else 0) * H μ) = ((D : ℝ)⁻¹) ^ Fintype.card A * H (realizedNoise z) := by simp [eq_comm] simp_rw [he] rw [Fintype.expect_eq_sum_div_card] simp only [Fintype.card_fun, Fintype.card_fin, Nat.cast_pow] rw [div_eq_mul_inv, inv_pow] rw [← Finset.mul_sum] exact mul_comm _ _
end MinUncutGames.Reduction.FiniteNoise
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563import Mathlibimport OAI.Computability.MinUncut.Machines.MachineLazyTableRuntime
namespace OAI
namespace MinUncutGames.Foundations.Complexity.GraphCounterModel
open Turing
inductive ExtraTape where | input | archive | scratch | output deriving DecidableEq
protected abbrev ExtraTape.enumList : List ExtraTape := [.input, .archive, .scratch, .output]
protected theorem ExtraTape.enumList_getElem?_ctorIdx_eq (x : ExtraTape) : ExtraTape.enumList[x.ctorIdx]? = some x := by cases x <;> rfl
protected theorem ExtraTape.enumList_nodup : ExtraTape.enumList.Nodup := by decide
instance : Fintype ExtraTape where elems := ⟨ExtraTape.enumList, ExtraTape.enumList_nodup⟩ complete x := by cases x <;> decide
inductive ExtraLabel where | copyFirst | copySecond | seed | headerFirst | headerSecond | clearInput | clockCopy | archiveCopy | finalReverse deriving DecidableEq
protected abbrev ExtraLabel.enumList : List ExtraLabel := [.copyFirst, .copySecond, .seed, .headerFirst, .headerSecond, .clearInput, .clockCopy, .archiveCopy, .finalReverse]
protected theorem ExtraLabel.enumList_getElem?_ctorIdx_eq (x : ExtraLabel) : ExtraLabel.enumList[x.ctorIdx]? = some x := by cases x <;> rfl
protected theorem ExtraLabel.enumList_nodup : ExtraLabel.enumList.Nodup := by decide
instance : Fintype ExtraLabel where elems := ⟨ExtraLabel.enumList, ExtraLabel.enumList_nodup⟩ complete x := by cases x <;> decide
abbrev Tape := Fin 3 ⊕ ExtraTapeabbrev Label := Fin 5 ⊕ ExtraLabelabbrev Alphabet (_ : Tape) := Boolabbrev State := MachineLogCounter.State × Option Bool
def initialState : State := (MachineLogCounter.initialState, none)
def clockLabel : Option (Fin 5) → Option Label | none => some (.inr .clearInput) | some l => some (.inl l)
def clockStatement : TM2.Stmt MachineLogCounter.Alphabet (Fin 5) MachineLogCounter.State → TM2.Stmt Alphabet Label State | .push k f next => .push (.inl k) (fun state => f state.1) (clockStatement next) | .peek k f next => .peek (.inl k) (fun state x => (f state.1 x, state.2)) (clockStatement next) | .pop k f next => .pop (.inl k) (fun state x => (f state.1 x, state.2)) (clockStatement next) | .load f next => .load (fun state => (f state.1, state.2)) (clockStatement next) | .branch f yes no => .branch (fun state => f state.1) (clockStatement yes) (clockStatement no) | .goto f => .goto (fun state => .inl (f state.1)) | .halt => .goto (fun _ => .inr .clearInput)
def readHeader (again next : Label) : TM2.Stmt Alphabet Label State := .pop (.inr .input) (fun state head => (state.1, head)) (.branch (fun state => state.2.getD false) (.push (.inl 0) (fun _ => true) (.goto fun _ => again)) (.load (fun state => (state.1, none)) (.goto fun _ => next)))
def program : Label → TM2.Stmt Alphabet Label State | .inl l => clockStatement (MachineLogCounter.program l) | .inr .copyFirst => Reduction.MachineTransfer.loopAt (.inr .input) (.inr .scratch) id false (.inr .copyFirst) (some (.inr .copySecond)) | .inr .copySecond => MachineCopy.forkLoop (.inr .scratch) (.inr .input) (.inr .archive) false (.inr .copySecond) (some (.inr .seed)) | .inr .seed => .push (.inl 0) (fun _ => false) (.goto fun _ => .inr .headerFirst) | .inr .headerFirst => readHeader (.inr .headerFirst) (.inr .headerSecond) | .inr .headerSecond => readHeader (.inr .headerSecond) (.inl 0) | .inr .clearInput => MachineDrain.drain (.inr .input) (.inr .clearInput) (some (.inr .clockCopy)) | .inr .clockCopy => Reduction.MachineTransfer.loopAt (.inl 2) (.inr .scratch) id false (.inr .clockCopy) (some (.inr .archiveCopy)) | .inr .archiveCopy => Reduction.MachineTransfer.loopAt (.inr .archive) (.inr .scratch) id false (.inr .archiveCopy) (some (.inr .finalReverse)) | .inr .finalReverse => Reduction.MachineTransfer.loopAt (.inr .scratch) (.inr .output) id false (.inr .finalReverse) none
def machine : FinTM2 where K := Tape k₀ := .inr .input k₁ := .inr .output Γ := Alphabet Λ := Label main := .inr .copyFirst σ := State initialState := initialState m := program
def clockTapes (tapes : Fin 3 → List Bool) (extra : ExtraTape → List Bool) : Tape → List Bool | .inl k => tapes k | .inr k => extra k
def clockConfiguration (extra : ExtraTape → List Bool) (register : Option Bool) (c : TM2.Cfg MachineLogCounter.Alphabet (Fin 5) MachineLogCounter.State) : TM2.Cfg Alphabet Label State := ⟨clockLabel c.l, (c.var, register), clockTapes c.stk extra⟩
theorem clockTapes_update (tapes : Fin 3 → List Bool) (extra : ExtraTape → List Bool) (k : Fin 3) (word : List Bool) : clockTapes (Function.update tapes k word) extra = Function.update (clockTapes tapes extra) (.inl k) word := by funext tape cases tape <;> simp [clockTapes, Function.comp_def]
theorem clockStatement_simulation (extra : ExtraTape → List Bool) (register : Option Bool) (statement : TM2.Stmt MachineLogCounter.Alphabet (Fin 5) MachineLogCounter.State) (state : MachineLogCounter.State) (tapes : Fin 3 → List Bool) : TM2.stepAux (clockStatement statement) (state, register) (clockTapes tapes extra) = clockConfiguration extra register (TM2.stepAux statement state tapes) := by induction statement generalizing state tapes with | push k f next ih => simp only [clockStatement, TM2.stepAux, clockTapes] rw [← clockTapes_update] exact ih state (Function.update tapes k (f state :: tapes k)) | peek k f next ih => simpa only [clockStatement, TM2.stepAux, clockTapes] using ih (f state (tapes k).head?) tapes | pop k f next ih => simp only [clockStatement, TM2.stepAux, clockTapes] rw [← clockTapes_update] exact ih (f state (tapes k).head?) (Function.update tapes k (tapes k).tail) | load f next ih => simpa only [clockStatement, TM2.stepAux] using ih (f state) tapes | branch f yes no ihYes ihNo => cases h : f state with | false => simpa only [clockStatement, TM2.stepAux, h, Bool.cond_false] using ihNo state tapes | true => simpa only [clockStatement, TM2.stepAux, h, Bool.cond_true] using ihYes state tapes | goto f => rfl | halt => rfl
theorem clockStep (extra : ExtraTape → List Bool) (register : Option Bool) (a b : MachineLogCounter.machine.Cfg) (h : MachineLogCounter.machine.step a = some b) : TM2.step program (clockConfiguration extra register a) = some (clockConfiguration extra register b) := by cases a with | mk label state tapes => cases label with | none => cases h | some label => have hb := Option.some.inj h subst b exact congrArg some (clockStatement_simulation extra register (MachineLogCounter.program label) state tapes)
def clockInTime (extra : ExtraTape → List Bool) (register : Option Bool) (n : Nat) : StateTransition.EvalsToInTime (TM2.step program) (clockConfiguration extra register (initList MachineLogCounter.machine (encodeWord n))) (some (clockConfiguration extra register (haltList MachineLogCounter.machine (encodeWord (n.log2 + 1))))) (8 * n + 4) := MachineComposition.liftExecutionInTime _ _ (clockConfiguration extra register) (clockStep extra register) (MachineLogCounter.outputsInTime n)
open Turing
def startExtra (input archive : List Bool) : ExtraTape → List Bool | .input => input | .archive => archive | _ => []
def startMemory (input archive sum : List Bool) : Tape → List Bool | .inl k => if k = 0 then sum else [] | .inr k => startExtra input archive k
theorem startMemory_input_update (input archive sum replacement : List Bool) : Function.update (startMemory input archive sum) (.inr .input) replacement = startMemory replacement archive sum := by funext tape cases tape with | inl k => simp [startMemory] | inr k => cases k <;> simp [startMemory, startExtra]
theorem startMemory_sum_update (input archive sum replacement : List Bool) : Function.update (startMemory input archive sum) (.inl 0) replacement = startMemory input archive replacement := by funext tape cases tape with | inl k => by_cases h : k = 0 <;> simp [startMemory, h] | inr k => simp [startMemory]
theorem headerStep_zero (again next : Label) (atHeader : program again = readHeader again next) (suffix archive : List Bool) (sum : Nat) (state : MachineLogCounter.State) (register : Option Bool) : TM2.step program ⟨some again, (state, register), startMemory (encodeWord 0 ++ suffix) archive (encodeWord sum)⟩ = some ⟨some next, (state, none), startMemory suffix archive (encodeWord sum)⟩ := by change some (TM2.stepAux (program again) _ _) = _ rw [atHeader] simp only [readHeader, TM2.stepAux, startMemory, startExtra, encodeWord, List.replicate_zero, List.nil_append, List.singleton_append, List.head?_cons, List.tail_cons, Option.getD_some, Bool.cond_false] rw [startMemory_input_update]
theorem headerStep_succ (again next : Label) (atHeader : program again = readHeader again next) (n sum : Nat) (suffix archive : List Bool) (state : MachineLogCounter.State) (register : Option Bool) : TM2.step program ⟨some again, (state, register), startMemory (encodeWord (n + 1) ++ suffix) archive (encodeWord sum)⟩ = some ⟨some again, (state, some true), startMemory (encodeWord n ++ suffix) archive (encodeWord (sum + 1))⟩ := by change some (TM2.stepAux (program again) _ _) = _ rw [atHeader] simp only [readHeader, TM2.stepAux, startMemory, startExtra, encodeWord, List.replicate_succ, List.cons_append, List.head?_cons, List.tail_cons, Option.getD_some, Bool.cond_true] rw [startMemory_input_update, startMemory_sum_update] rfl
theorem headerTrace (again next : Label) (atHeader : program again = readHeader again next) (n sum : Nat) (suffix archive : List Bool) (state : MachineLogCounter.State) (register : Option Bool) : (MachineComposition.advance (TM2.step program))^[n + 1] (some ⟨some again, (state, register), startMemory (encodeWord n ++ suffix) archive (encodeWord sum)⟩) = some ⟨some next, (state, none), startMemory suffix archive (encodeWord (n + sum))⟩ := by induction n generalizing sum register with | zero => simpa only [Nat.zero_add, Function.iterate_one, MachineComposition.advance_some] using headerStep_zero again next atHeader suffix archive sum state register | succ n ih => rw [Function.iterate_succ_apply, MachineComposition.advance_some] rw [headerStep_succ again next atHeader n sum suffix archive state register] simpa only [Nat.add_assoc, Nat.add_comm 1 sum] using ih (sum + 1) (some true)
def headerInTime (again next : Label) (atHeader : program again = readHeader again next) (n sum : Nat) (suffix archive : List Bool) (state : MachineLogCounter.State) (register : Option Bool) : StateTransition.EvalsToInTime (TM2.step program) ⟨some again, (state, register), startMemory (encodeWord n ++ suffix) archive (encodeWord sum)⟩ (some ⟨some next, (state, none), startMemory suffix archive (encodeWord (n + sum))⟩) (n + 1) where steps := n + 1 evals_in_steps := headerTrace again next atHeader n sum suffix archive state register steps_le_m := le_rfl
theorem initialMemory (word : List Bool) : initList machine word = ⟨some (.inr .copyFirst), initialState, startMemory word [] []⟩ := by have ht : (initList machine word).stk = startMemory word [] [] := by funext tape cases tape with | inl k => simp [initList, machine, startMemory] | inr k => cases k <;> simp [initList, machine, startMemory, startExtra] all_goals rfl exact congrArg (TM2.Cfg.mk _ _) ht
theorem clockInitialMemory (word rest : List Bool) (sum : Nat) : clockConfiguration (startExtra rest word) none (initList MachineLogCounter.machine (encodeWord sum)) = ⟨some (.inl 0), initialState, startMemory rest word (encodeWord sum)⟩ := by have ht : clockTapes (initList MachineLogCounter.machine (encodeWord sum)).stk (startExtra rest word) = startMemory rest word (encodeWord sum) := by funext tape cases tape with | inl k => fin_cases k <;> simp [clockTapes, initList, MachineLogCounter.machine, startMemory] all_goals rfl | inr k => rfl exact congrArg (TM2.Cfg.mk _ _) ht
def startInTime (n m : Nat) (rest : List Bool) : StateTransition.EvalsToInTime machine.step (initList machine (encodeWords [n, m] ++ rest)) (some (clockConfiguration (startExtra rest (encodeWords [n, m] ++ rest)) none (initList MachineLogCounter.machine (encodeWord (n + m))))) (2 * ((encodeWords [n, m] ++ rest).length + 1) + 1 + (n + 1) + (m + 1)) := by let word := encodeWords [n, m] ++ rest let b₀ := startMemory word [] [] let b₁ := startMemory word word [] let b₂ := startMemory word word (encodeWord 0) have hc : Function.update b₀ (.inr .archive) (b₀ (.inr .input) ++ b₀ (.inr .archive)) = b₁ := by funext tape cases tape with | inl k => simp [b₀, b₁, startMemory] | inr k => cases k <;> simp [b₀, b₁, startMemory, startExtra] let copy := MachineCopy.copyInTime (.inr ExtraTape.input) (.inr ExtraTape.archive) (.inr ExtraTape.scratch) (by decide) (by decide) (by decide) false (.inr ExtraLabel.copyFirst) (.inr ExtraLabel.copySecond) (some (.inr ExtraLabel.seed)) program rfl rfl b₀ rfl MachineLogCounter.initialState none have copy' : StateTransition.EvalsToInTime (TM2.step program) ⟨some (.inr .copyFirst), initialState, b₀⟩ (some ⟨some (.inr .seed), initialState, b₁⟩) (2 * (word.length + 1)) := by have h := copy rw [hc] at h simpa only [initialState, show b₀ (.inr .input) = word from rfl] using h have seed : StateTransition.EvalsToInTime (TM2.step program) ⟨some (.inr .seed), initialState, b₁⟩ (some ⟨some (.inr .headerFirst), initialState, b₂⟩) 1 := by refine ⟨⟨1, ?_⟩, le_rfl⟩ change some (TM2.stepAux (program (.inr .seed)) initialState b₁) = _ simp only [program, TM2.stepAux, b₁, startMemory] rw [startMemory_sum_update] rfl have first := headerInTime (.inr .headerFirst) (.inr .headerSecond) rfl n 0 (encodeWord m ++ rest) word MachineLogCounter.initialState none have first' : StateTransition.EvalsToInTime (TM2.step program) ⟨some (.inr .headerFirst), initialState, b₂⟩ (some ⟨some (.inr .headerSecond), initialState, startMemory (encodeWord m ++ rest) word (encodeWord n)⟩) (n + 1) := by simpa only [b₂, initialState, word, encodeWords, List.append_nil, List.append_assoc, Nat.add_zero] using first have second := headerInTime (.inr .headerSecond) (.inl 0) rfl m n rest word MachineLogCounter.initialState none have second' : StateTransition.EvalsToInTime (TM2.step program) ⟨some (.inr .headerSecond), initialState, startMemory (encodeWord m ++ rest) word (encodeWord n)⟩ (some ⟨some (.inl 0), initialState, startMemory rest word (encodeWord (n + m))⟩) (m + 1) := by simpa only [initialState, Nat.add_comm m n] using second let p₀ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ copy' seed let p₁ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₀ first' let p := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p₁ second' rw [initialMemory, clockInitialMemory] exact { toEvalsTo := p.toEvalsTo steps_le_m := by have h := p.steps_le_m change p.steps ≤ 2 * (word.length + 1) + 1 + (n + 1) + (m + 1) omega }
end MinUncutGames.Foundations.Complexity.GraphCounterModel
namespace MinUncutGames.Foundations.Complexity.GraphCounterFinish
open Turing GraphCounterModel
def extraTapes (rest original : List Bool) : ExtraTape → List Bool | .input => rest | .archive => original | _ => []
def frame (input archive counter reversed output : List Bool) : Tape → List Bool | .inl i => if i = 2 then counter else [] | .inr .input => input | .inr .archive => archive | .inr .scratch => reversed | .inr .output => output
theorem trace_trans {α : Type*} (f : α → α) {a b : Nat} {x y z : α} (first : f^[a] x = y) (second : f^[b] y = z) : f^[a + b] x = z := by rw [Nat.add_comm, Function.iterate_add_apply, first, second]
theorem start_eq (counter rest original : List Bool) : clockConfiguration (extraTapes rest original) none (haltList MachineLogCounter.machine counter) = ⟨some (.inr .clearInput), initialState, frame rest original counter [] []⟩ := by rw [MachineLogCounter.haltList_eq] unfold clockConfiguration congr 1 funext tape cases tape with | inl i => fin_cases i <;> simp [clockTapes, frame, MachineLogCounter.configuration, MachineLogCounter.rawTapes] | inr k => cases k <;> rfl
theorem finish_eq (word : List Bool) : (⟨none, initialState, frame [] [] [] [] word⟩ : TM2.Cfg Alphabet Label State) = haltList machine word := by unfold haltList congr 1 funext tape cases tape with | inl i => simp [machine, frame] | inr k => cases k <;> simp [machine, frame] all_goals rfl
theorem drainTrace (rest original counter : List Bool) : (MachineComposition.advance (TM2.step program))^[rest.length + 1] (some ⟨some (.inr .clearInput), initialState, frame rest original counter [] []⟩) = some ⟨some (.inr .clockCopy), initialState, frame [] original counter [] []⟩ := by have h := (MachineDrain.drainInTime (Sum.inr ExtraTape.input) (Sum.inr ExtraLabel.clearInput) (some (.inr .clockCopy)) program rfl (frame rest original counter [] []) MachineLogCounter.initialState none).evals_in_steps change (MachineComposition.advance (TM2.step program))^[rest.length + 1] (some ⟨some (.inr .clearInput), initialState, frame rest original counter [] []⟩) = _ at h have update : Function.update (frame rest original counter [] []) (.inr .input) [] = frame [] original counter [] [] := by funext tape cases tape with | inl i => simp [frame] | inr k => cases k <;> simp [frame] simpa only [update, initialState] using h
theorem clockCopyTrace (original counter : List Bool) : (MachineComposition.advance (TM2.step program))^[counter.length + 1] (some ⟨some (.inr .clockCopy), initialState, frame [] original counter [] []⟩) = some ⟨some (.inr .archiveCopy), initialState, frame [] original [] counter.reverse []⟩ := by have h := (Reduction.MachineTransfer.transferAtInTime (Sum.inl (2 : Fin 3)) (Sum.inr ExtraTape.scratch) (by decide) id false (.inr .clockCopy) (some (.inr .archiveCopy)) program rfl (frame [] original counter [] []) MachineLogCounter.initialState none).evals_in_steps change (MachineComposition.advance (TM2.step program))^[counter.length + 1] (some ⟨some (.inr .clockCopy), initialState, frame [] original counter [] []⟩) = _ at h have update : Reduction.MachineTransfer.tapesAt (Sum.inl (2 : Fin 3)) (Sum.inr ExtraTape.scratch) (frame [] original counter [] []) [] ((frame [] original counter [] [] (.inl 2)).reverse.map id ++ frame [] original counter [] [] (.inr .scratch)) = frame [] original [] counter.reverse [] := by funext tape cases tape with | inl i => fin_cases i <;> simp [Reduction.MachineTransfer.tapesAt, frame] | inr k => cases k <;> simp [Reduction.MachineTransfer.tapesAt, frame] simpa only [update, initialState] using h
theorem archiveCopyTrace (original counter : List Bool) : (MachineComposition.advance (TM2.step program))^[original.length + 1] (some ⟨some (.inr .archiveCopy), initialState, frame [] original [] counter.reverse []⟩) = some ⟨some (.inr .finalReverse), initialState, frame [] [] [] (original.reverse ++ counter.reverse) []⟩ := by have h := (Reduction.MachineTransfer.transferAtInTime (Sum.inr ExtraTape.archive) (Sum.inr ExtraTape.scratch) (by decide) id false (.inr .archiveCopy) (some (.inr .finalReverse)) program rfl (frame [] original [] counter.reverse []) MachineLogCounter.initialState none).evals_in_steps change (MachineComposition.advance (TM2.step program))^[original.length + 1] (some ⟨some (.inr .archiveCopy), initialState, frame [] original [] counter.reverse []⟩) = _ at h have update : Reduction.MachineTransfer.tapesAt (Sum.inr ExtraTape.archive) (Sum.inr ExtraTape.scratch) (frame [] original [] counter.reverse []) [] ((frame [] original [] counter.reverse [] (.inr .archive)).reverse.map id ++ frame [] original [] counter.reverse [] (.inr .scratch)) = frame [] [] [] (original.reverse ++ counter.reverse) [] := by funext tape cases tape with | inl i => simp [Reduction.MachineTransfer.tapesAt, frame] | inr k => cases k <;> simp [Reduction.MachineTransfer.tapesAt, frame] simpa only [update, initialState] using h
theorem reverseTrace (original counter : List Bool) : (MachineComposition.advance (TM2.step program))^[original.length + counter.length + 1] (some ⟨some (.inr .finalReverse), initialState, frame [] [] [] (original.reverse ++ counter.reverse) []⟩) = some (haltList machine (counter ++ original)) := by have h := (Reduction.MachineTransfer.transferAtInTime (Sum.inr ExtraTape.scratch) (Sum.inr ExtraTape.output) (by decide) id false (.inr .finalReverse) none program rfl (frame [] [] [] (original.reverse ++ counter.reverse) []) MachineLogCounter.initialState none).evals_in_steps change (MachineComposition.advance (TM2.step program))^[ (original.reverse ++ counter.reverse).length + 1] (some ⟨some (.inr .finalReverse), initialState, frame [] [] [] (original.reverse ++ counter.reverse) []⟩) = _ at h have update : Reduction.MachineTransfer.tapesAt (Sum.inr ExtraTape.scratch) (Sum.inr ExtraTape.output) (frame [] [] [] (original.reverse ++ counter.reverse) []) [] ((frame [] [] [] (original.reverse ++ counter.reverse) [] (.inr .scratch)).reverse.map id ++ frame [] [] [] (original.reverse ++ counter.reverse) [] (.inr .output)) = frame [] [] [] [] (counter ++ original) := by funext tape cases tape with | inl i => simp [Reduction.MachineTransfer.tapesAt, frame] | inr k => cases k <;> simp [Reduction.MachineTransfer.tapesAt, frame] rw [update] at h rw [← finish_eq] simpa only [List.length_append, List.length_reverse, initialState] using! h
theorem finishTrace (counter rest original : List Bool) : (MachineComposition.advance (TM2.step program))^[ rest.length + 2 * counter.length + 2 * original.length + 4] (some (clockConfiguration (extraTapes rest original) none (haltList MachineLogCounter.machine counter))) = some (haltList machine (counter ++ original)) := by rw [start_eq] have total := trace_trans _ (trace_trans _ (trace_trans _ (drainTrace rest original counter) (clockCopyTrace original counter)) (archiveCopyTrace original counter)) (reverseTrace original counter) simpa only [show rest.length + 1 + (counter.length + 1) + (original.length + 1) + (original.length + counter.length + 1) = rest.length + 2 * counter.length + 2 * original.length + 4 by omega] using total
def finishInTime (counter rest original : List Bool) : StateTransition.EvalsToInTime (TM2.step program) (clockConfiguration (extraTapes rest original) none (haltList MachineLogCounter.machine counter)) (some (haltList machine (counter ++ original))) (rest.length + 2 * counter.length + 2 * original.length + 4) where steps := rest.length + 2 * counter.length + 2 * original.length + 4 evals_in_steps := finishTrace counter rest original steps_le_m := le_rfl
end MinUncutGames.Foundations.Complexity.GraphCounterFinish
namespace MinUncutGames.Foundations.Complexity.GraphCounterPrefix
open Turing PCP GraphCounterModel GraphCounterFinish
def rawOutput (n m : Nat) (rest : List Bool) : List Bool := encodeWord ((n + m).log2 + 1) ++ (encodeWords [n, m] ++ rest)
def rawInTime (n m : Nat) (rest : List Bool) : TM2OutputsInTime machine (encodeWords [n, m] ++ rest) (some (rawOutput n m rest)) (20 * (encodeWords [n, m] ++ rest).length + 30) := by let original := encodeWords [n, m] ++ rest let start := startInTime n m rest let clock := clockInTime (extraTapes rest original) none (n + m) let finish := finishInTime (encodeWord ((n + m).log2 + 1)) rest original have start' : StateTransition.EvalsToInTime (TM2.step program) (initList machine original) (some (clockConfiguration (extraTapes rest original) none (initList MachineLogCounter.machine (encodeWord (n + m))))) (2 * (original.length + 1) + 1 + (n + 1) + (m + 1)) := start let first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ start' clock let total := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first finish refine { toEvalsTo := total.toEvalsTo, steps_le_m := ?_ } have bound := total.steps_le_m have hlog := Nat.log2_le_self (n + m) have hlength : original.length = n + m + 2 + rest.length := by simp only [original, List.length_append, encodeWords, encodeWord_length, List.length_nil] omega simp only [encodeWord_length] at bound change total.steps ≤ 20 * original.length + 30 omega
def count (table : GraphTables.Table) : Nat := (table.vertices + table.darts).log2 + 1
def output (table : GraphTables.Table) : List Bool := encodeWord (count table) ++ GraphTables.tableBits table
def rowsBits (table : GraphTables.Table) : List Bool := encodeWords ((GraphTables.rowList table).flatMap GraphTables.rowWords)
theorem tableBits_decomposition (table : GraphTables.Table) : GraphTables.tableBits table = encodeWords [table.vertices, table.darts] ++ rowsBits table := encodeWords_append _ _
def outputsInTime (table : GraphTables.Table) : TM2OutputsInTime machine (GraphTables.tableBits table) (some (output table)) (20 * (GraphTables.tableBits table).length + 30) := by have run := rawInTime table.vertices table.darts (rowsBits table) simpa only [rawOutput, output, count, tableBits_decomposition] using run
noncomputable def computableInPolyTime : TM2ComputableInPolyTime GraphTables.tableBits id output where tm := machine inputAlphabet := Equiv.refl Bool outputAlphabet := Equiv.refl Bool time := 20 * Polynomial.X + 30 outputsFun table := by change TM2OutputsInTime machine ((GraphTables.tableBits table).map id) (some ((output table).map id)) ((20 * Polynomial.X + 30 : Polynomial Nat).eval (GraphTables.tableBits table).length) have input_eq : @List.map (machine.Γ machine.k₀) (machine.Γ machine.k₀) id (GraphTables.tableBits table) = GraphTables.tableBits table := List.map_id _ have output_eq : @List.map (machine.Γ machine.k₁) (machine.Γ machine.k₁) id (output table) = output table := List.map_id _ rw [input_eq, output_eq] simpa only [Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_ofNat, Polynomial.eval_X] using outputsInTime table
end MinUncutGames.Foundations.Complexity.GraphCounterPrefix
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import Mathlibimport OAI.Computability.MinUncut.PCP.TableIterationimport OAI.Computability.MinUncut.Games.GraphCounterModelimport OAI.Computability.MinUncut.Machines.PCPIterationMachine
namespace OAI
sectionnamespace MinUncutGames.Foundations.Complexity.GraphIterationBounds
open PCP RoundTables
def inputBits (input : Input) : List Bool := GraphTables.tableBits input.val
def countedBits (input : Input) : List Bool := GraphCounterPrefix.output input.val
def words (H : BaseTable) (input : Input) (i : Nat) : List Bool := GraphTables.tableBits (TableIteration.runTables H i input.val)
def count (input : Input) : Nat := GraphCounterPrefix.count input.val
noncomputable def lengthPolynomial : Polynomial Nat := (GraphTableComplexity.encodingPolynomial 64).comp (PCPIterationMachine.sizePolynomial sizeFactor)
theorem inputBits_le_countedBits (input : Input) : (inputBits input).length ≤ (countedBits input).length := by simp only [inputBits, countedBits, GraphCounterPrefix.output, List.length_append] omega
theorem size_le_inputBits (input : Input) : size input ≤ (inputBits input).length := by have h := GraphTableComplexity.size_add_two_le_bits input.val unfold size inputBits omega
theorem count_le (input : Input) : count input ≤ (countedBits input).length + 1 := (PCPIterationMachine.rounds_le (size input)).trans (Nat.add_le_add_right ((size_le_inputBits input).trans (inputBits_le_countedBits input)) 1)
theorem intermediate_size (H : BaseTable) (input : Input) (i : Nat) (hi : i ≤ count input) : size (TableIteration.run H i input) ≤ PCPIterationMachine.sizeEnvelope sizeFactor (size input) := by apply PCPIterationMachine.semanticSize_bound (fun j => size (TableIteration.run H j input)) sizeFactor (size input) sizeFactor_positive (Nat.le_succ _) _ i hi intro j _ exact step_size H (TableIteration.run H j input)
theorem intermediate_bits (H : BaseTable) (input : Input) (i : Nat) (hi : i ≤ count input) : (words H input i).length ≤ lengthPolynomial.eval (countedBits input).length := by have hsize := intermediate_size H input i hi have hinput := (size_le_inputBits input).trans (inputBits_le_countedBits input) have heval := MachineComposition.natPolynomial_eval_mono (PCPIterationMachine.sizePolynomial sizeFactor) hinput rw [PCPIterationMachine.sizePolynomial_eval, PCPIterationMachine.sizePolynomial_eval] at heval have hs := hsize.trans heval have htable : (TableIteration.runTables H i input.val).vertices + (TableIteration.runTables H i input.val).darts ≤ PCPIterationMachine.sizeEnvelope sizeFactor (countedBits input).length := by rw [← TableIteration.run_val] exact hs rw [lengthPolynomial, Polynomial.eval_comp, PCPIterationMachine.sizePolynomial_eval] exact GraphTableComplexity.bits_le_of_size_le _ htable
noncomputable def runtimePolynomial (bodyTime : Polynomial Nat) : Polynomial Nat := (Polynomial.X + 1) * (bodyTime.comp lengthPolynomial + 2 * lengthPolynomial + 4) + 2 * lengthPolynomial + 4
theorem runtimePolynomial_eval (bodyTime : Polynomial Nat) (N : Nat) : (runtimePolynomial bodyTime).eval N = (N + 1) * (bodyTime.eval (lengthPolynomial.eval N) + 2 * lengthPolynomial.eval N + 4) + 2 * lengthPolynomial.eval N + 4 := by simp only [runtimePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_X, Polynomial.eval_one, Polynomial.eval_ofNat, Polynomial.eval_comp]
end MinUncutGames.Foundations.Complexity.GraphIterationBounds
end
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import Mathlibimport OAI.Computability.MinUncut.Estimates.OuterSamplingimport OAI.Computability.MinUncut.Estimates.PatchExpectation
namespace OAI
sectionnoncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Innerattribute [local instance] Classical.propDecidablevariable {Name I S : Type*} [Fintype Name] [Fintype I] [Fintype S] [Nonempty S]
def sampledEquations (equations : S → Equation Name) (w : I → S × Fin 3) : I → Equation Name := fun j => equations (w j).1
def sampledPositions (w : I → S × Fin 3) : I → Fin 3 := fun j => (w j).2
omit [Fintype Name] [Fintype I] [Fintype S] [Nonempty S] inlemma sampledEquations_patch (equations : S → Equation Name) (A : I → Prop) (bg : I → S × Fin 3) (w : {i // A i} → S × Fin 3) : sampledEquations equations (patch A bg w)= patch A (sampledEquations equations bg) (sampledEquations equations w) := patch_comp A bg w (fun x => equations x.1)
omit [Fintype Name] [Fintype I] [Fintype S] [Nonempty S] inlemma sampledPositions_patch (A : I → Prop) (bg : I → S × Fin 3) (w : {i // A i} → S × Fin 3) : sampledPositions (patch A bg w)= patch A (sampledPositions bg) (sampledPositions w) := patch_comp A bg w Prod.snd
theorem hint_section_bound (equations : S → Equation Name) (hsound : ∀ s : Name → F₂, equationFraction equations s ≤ 3/4) {q : ℕ} (strategy : HintedStrategy Name I q) (A : I → Prop) (hidden : I → Bool) (hA : ∀ i, A i → hidden i=true) (c : HintCoefficients I q) (hzero : ∀ k i, A i → (c k).2.1 i=0) (bg : I → S × Fin 3) : (𝔼 w : {i // A i} → S × Fin 3, if hintedWins strategy (sampledEquations equations (patch A bg w)) hidden (sampledPositions (patch A bg w)) c then (1 : ℝ) else 0) ≤ repetitionRate ^ Fintype.card {i // A i} := by classical obtain ⟨a,b,hsim⟩ := active_simulation strategy A hidden hA c hzero (sampledEquations equations bg) (sampledPositions bg) have hrep := ordinary_repetition_on equations hsound a b apply le_trans (b := (𝔼 w : {i // A i} → S × Fin 3, if (∀ j, ordinaryAccepts (equations (w j).1) ((equations (w j).1).names (w j).2) (a (fun i => equations (w i).1) j) (b (fun i => (equations (w i).1).names (w i).2) j)=true) then (1 : ℝ) else 0)) ?_ (by convert hrep using 1; congr 1 exact Finset.ext (by intro x; simp)) refine Finset.expect_le_expect (fun w _ => ?_) split_ifs with hw hr hr · rfl · exfalso apply hr have hwin := hw rw [sampledEquations_patch,sampledPositions_patch] at hwin exact hsim (sampledEquations equations w) (sampledPositions w) hwin · norm_num · rfl
theorem hint_fixed_coefficients_bound (equations : S → Equation Name) (hsound : ∀ s : Name → F₂, equationFraction equations s ≤ 3/4) {q : ℕ} (strategy : HintedStrategy Name I q) (A : I → Prop) (hidden : I → Bool) (hA : ∀ i, A i → hidden i=true) (c : HintCoefficients I q) (hzero : ∀ k i, A i → (c k).2.1 i=0) : (𝔼 w : I → S × Fin 3, if hintedWins strategy (sampledEquations equations w) hidden (sampledPositions w) c then (1 : ℝ) else 0) ≤ repetitionRate ^ Fintype.card {i // A i} := expect_le_of_active_sections A _ _ (hint_section_bound equations hsound strategy A hidden hA c hzero)
end MinUncut.Outer
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154import Mathlibimport OAI.Computability.MinUncut.Games.Sampling
namespace OAI
noncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Innerattribute [local instance] Classical.propDecidablevariable {Name I : Type*} [Fintype I]
abbrev HintCoefficients (I : Type*) (q : ℕ) := Fin q → (F₂ × ((I → F₂) × (I → Module.Dual F₂ Triple)))
def secondHints {q : ℕ} (V : I → SecondQuestion Name) (c : HintCoefficients I q) : Fin q → Forms (SecondAlphabet V) := fun k => hintGenerator V (c k)
def firstHints {q : ℕ} (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3) (c : HintCoefficients I q) : Fin q → Forms (FirstAlphabet U) := fun k => formPullback (projection U hidden pos) (secondHints (secondQuestion U hidden pos) c k)
structure HintedStrategy (Name I : Type*) [Fintype I] (q : ℕ) where first : (U : I → Equation Name) → (Fin q → Forms (FirstAlphabet U)) → FirstAlphabet U second : (V : I → SecondQuestion Name) → (Fin q → Forms (SecondAlphabet V)) → SecondAlphabet V
def hintedWins {q : ℕ} (strategy : HintedStrategy Name I q) (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3) (c : HintCoefficients I q) : Prop := projection U hidden pos (strategy.first U (firstHints U hidden pos c)) = strategy.second (secondQuestion U hidden pos) (secondHints (secondQuestion U hidden pos) c)
def patch {X : Type*} (A : I → Prop) (background : I → X) (active : {i // A i} → X) : I → X := fun i => if h : A i then active ⟨i,h⟩ else background i
omit [Fintype I] in@[simp] lemma patch_active {X : Type*} (A : I → Prop) (background : I → X) (active : {i // A i} → X) (i : {i // A i}) : patch A background active i = active i := by simp [patch,i.property]
omit [Fintype I] in@[simp] lemma patch_inactive {X : Type*} (A : I → Prop) (background : I → X) (active : {i // A i} → X) (i : I) (hi : ¬A i) : patch A background active i = background i := by simp [patch,hi]
omit [Fintype I] inlemma patch_comp {X Y : Type*} (A : I → Prop) (background : I → X) (active : {i // A i} → X) (f : X → Y) : (fun i => f (patch A background active i)) = patch A (fun i => f (background i)) (fun i => f (active i)) := by funext i by_cases h : A i <;> simp [patch,h]
def slotZero (v : SecondQuestion Name) : Fin (secondSlotCount v) := ⟨0,by cases v <;> exact Nat.zero_lt_succ _⟩
def readBit (V : I → SecondQuestion Name) (a : SecondAlphabet V) (i : I) : F₂ := a i (slotZero (V i))
omit [Fintype I] inlemma projection_hidden_bit (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3) (a : FirstAlphabet U) (i : I) (hi : hidden i=true) : readBit (secondQuestion U hidden pos) (projection U hidden pos a) i=(a i).val (pos i) := by change (slotProjection (U i) (hidden i) (pos i) (a i)) (slotZero (slotQuestion (U i) (hidden i) (pos i)))=_ rw [hi] rfl
lemma firstHints_position_independent {q : ℕ} (U : I → Equation Name) (hidden : I → Bool) (pos pos' : I → Fin 3) (c : HintCoefficients I q) (h : ∀ k j, hidden j=true → pos j≠pos' j → (c k).2.1 j=0) : firstHints U hidden pos c=firstHints U hidden pos' c := by funext k exact pulledHint_independent_active U hidden pos pos' _ _ _ (h k)
lemma ordinary_accepts_of_valid_coordinate (E : Equation Name) (a : alphabet E) (p : Fin 3) (b : F₂) (he : a.val p=b) : ordinaryAccepts E (E.names p) a.val b=true := by apply decide_eq_true refine ⟨a.property,?_⟩ intro p' hp' exact (a.property.2 p' p hp').trans he
omit [Fintype I] in
lemma secondQuestion_patch (A : I → Prop) (hidden : I → Bool) (hA : ∀ i, A i → hidden i=true) (bgU : I → Equation Name) (bgp : I → Fin 3) (U : {i // A i} → Equation Name) (p : {i // A i} → Fin 3) : secondQuestion (patch A bgU U) hidden (patch A bgp p) = patch A (secondQuestion bgU hidden bgp) (fun i => Sum.inl ((U i).names (p i))) := by funext i by_cases hi : A i · simp [patch,secondQuestion,slotQuestion,hA i hi,hi] · simp [patch,secondQuestion,hi]
end MinUncut.Outer
namespace MinUncut.Outeropen MinUncut.Innerattribute [local instance] Classical.propDecidablevariable {Name I : Type*} [Fintype I]
theorem active_simulation {q : ℕ} (strategy : HintedStrategy Name I q) (A : I → Prop) (hidden : I → Bool) (hA : ∀ i, A i → hidden i=true) (c : HintCoefficients I q) (hzero : ∀ k i, A i → (c k).2.1 i=0) (bgU : I → Equation Name) (bgp : I → Fin 3) : ∃ (a : ({i // A i} → Equation Name) → {i // A i} → Triple) (b : ({i // A i} → Name) → {i // A i} → F₂), ∀ (U : {i // A i} → Equation Name) (p : {i // A i} → Fin 3), hintedWins strategy (patch A bgU U) hidden (patch A bgp p) c → ∀ j, ordinaryAccepts (U j) ((U j).names (p j)) (a U j) (b (fun i => (U i).names (p i)) j)=true := by classical let p₀ : I → Fin 3 := patch A bgp (fun _ => 0) let first (U : {i // A i} → Equation Name) : FirstAlphabet (patch A bgU U) := strategy.first (patch A bgU U) (firstHints (patch A bgU U) hidden p₀ c) let V (y : {i // A i} → Name) : I → SecondQuestion Name := patch A (secondQuestion bgU hidden bgp) (fun i => Sum.inl (y i)) let second (y : {i // A i} → Name) : SecondAlphabet (V y) := strategy.second (V y) (secondHints (V y) c) let a := fun U (j : {i // A i}) => (first U j).val let b := fun y (j : {i // A i}) => readBit (V y) (second y) j refine ⟨a,b,?_⟩ intro U p hwin j have hints : firstHints (patch A bgU U) hidden (patch A bgp p) c = firstHints (patch A bgU U) hidden p₀ c := by apply firstHints_position_independent intro k i _ hdiff apply hzero k i by_contra hi exact hdiff (by simp [p₀,patch,hi]) have hv : secondQuestion (patch A bgU U) hidden (patch A bgp p) = V (fun i => (U i).names (p i)) := secondQuestion_patch A hidden hA bgU bgp U p unfold hintedWins at hwin rw [hints] at hwin have hb := congrArg (fun z => readBit (secondQuestion (patch A bgU U) hidden (patch A bgp p)) z j) hwin rw [projection_hidden_bit _ _ _ _ _ (hA j j.property)] at hb have hcoord : a U j (p j)=b (fun i => (U i).names (p i)) j := by simp only [patch_active] at hb rw [hv] at hb exact hb have hvalid : Valid (U j) (a U j) := by have hv' : Valid (patch A bgU U j) (a U j) := (first U j).property simpa only [patch_active] using hv' apply decide_eq_true refine ⟨hvalid,?_⟩ intro p' hp' exact (hvalid.2 p' (p j) hp').trans hcoord
end MinUncut.Outer
end
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import Mathlibimport OAI.Computability.MinUncut.Games.HintSectionsimport OAI.Computability.MinUncut.Estimates.CoefficientMoments
namespace OAI
sectionnoncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Innerattribute [local instance] Classical.propDecidable BinaryFourier.dualFintypevariable {Name I S : Type*} [Fintype Name] [Fintype I] [Fintype S] [Nonempty S]
def hintedAcceptance {q : ℕ} (strategy : HintedStrategy Name I q) (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3) (L : Fin q → Forms (SecondAlphabet (secondQuestion U hidden pos))) : Prop := projection U hidden pos (strategy.first U (fun k => formPullback (projection U hidden pos) (L k))) = strategy.second (secondQuestion U hidden pos) L
omit [Fintype Name] [Fintype S] [Nonempty S] inlemma hintedAcceptance_generated {q : ℕ} (strategy : HintedStrategy Name I q) (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3) (c : HintCoefficients I q) : hintedAcceptance strategy U hidden pos (hintTupleGenerator (secondQuestion U hidden pos) q c) ↔ hintedWins strategy U hidden pos c := Iff.rfl
theorem shared_hint_soundness (equations : S → Equation Name) (hsound : ∀ s : Name → F₂, equationFraction equations s ≤ 3/4) {q : ℕ} (strategy : HintedStrategy Name I q) (hidden : I → Bool) : (𝔼 w : I → S × Fin 3, 𝔼 L : Fin q → Forms (SecondAlphabet (secondQuestion (sampledEquations equations w) hidden (sampledPositions w))), if hintedAcceptance strategy (sampledEquations equations w) hidden (sampledPositions w) L then (1 : ℝ) else 0) ≤ hintRate q ^ Fintype.card {i // hidden i=true} := by classical have hsample (w : I → S × Fin 3) : (𝔼 L : Fin q → Forms (SecondAlphabet (secondQuestion (sampledEquations equations w) hidden (sampledPositions w))), if hintedAcceptance strategy (sampledEquations equations w) hidden (sampledPositions w) L then (1 : ℝ) else 0) = (𝔼 c : HintCoefficients I q, if hintedWins strategy (sampledEquations equations w) hidden (sampledPositions w) c then (1 : ℝ) else 0) := by exact (uniform_hintTupleGenerator _ q (fun L => if hintedAcceptance strategy (sampledEquations equations w) hidden (sampledPositions w) L then (1 : ℝ) else 0)).symm simp_rw [hsample] rw [Finset.expect_comm] calc _ ≤ 𝔼 c : HintCoefficients I q, repetitionRate ^ Fintype.card {i // Active hidden (coefficientVectors q c) i} := by apply Finset.expect_le_expect intro c _ apply hint_fixed_coefficients_bound equations hsound strategy (Active hidden (coefficientVectors q c)) hidden (fun _ hi => hi.1) c intro k i hi exact congrFun hi.2 k _ = _ := coefficient_active_expect q hidden
lemma shared_hint_rate_vanishes (q : ℕ) {ε : ℝ} (hε : 0<ε) : ∃ n : ℕ, hintRate q ^ n < ε := by exact (tendsto_pow_atTop_nhds_zero_of_lt_one (hintRate_nonnegative q) (hintRate_lt_one q)).eventually (gt_mem_nhds hε) |>.exists
end MinUncut.Outer
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527import Mathlibimport OAI.Computability.MinUncut.Estimates.SamplerAssemblyimport OAI.Computability.MinUncut.Games.Actual
namespace OAI
sectionnamespace MinUncutGames.Reduction.IncidenceProbability
variable {Variable : Type*} {Index : Type*} {I : Type*} {Coin : Type*}
open Incidenceopen scoped BigOperators
theorem sum_bool_indicator_eq_count_ofFn {n : Nat} (p : Fin n → Bool) : (∑ i, if p i then (1 : ℚ) else 0) = ((List.ofFn p).countP id : ℚ) := by induction n with | zero => simp | succ n ih => rw [Fin.sum_univ_succ, List.ofFn_succ, List.countP_cons, ih] cases p 0 <;> simp [add_comm]
theorem expect_bool_indicator_eq_count_ofFn {n : Nat} (p : Fin n → Bool) : Finset.univ.expect (fun i : Fin n => if p i then (1 : ℚ) else 0) = ((List.ofFn p).countP id : ℚ) / n := by rw [Fintype.expect_eq_sum_div_card, sum_bool_indicator_eq_count_ofFn] simp
def slotOfFin (i : Fin 3) : Slot := if i = 0 then .first else if i = 1 then .second else .third
def slotPredicate (e : Equation Variable) (alice : Triple) (g : Variable → Bool) (slot : Fin 3) : Prop := parity alice = e.rhs ∧ bitAt alice (slotOfFin slot) = g (nameAt e (slotOfFin slot))
instance (e : Equation Variable) (alice : Triple) (g : Variable → Bool) (slot : Fin 3) : Decidable (slotPredicate e alice g slot) := inferInstanceAs (Decidable (_ ∧ _))
def slotAcceptance (e : Equation Variable) (alice : Triple) (g : Variable → Bool) (slot : Fin 3) : ℚ := if slotPredicate e alice g slot then 1 else 0
theorem slot_predicate_is_question_predicate (e : Equation Variable) (h12 : e.first ≠ e.second) (h13 : e.first ≠ e.third) (h23 : e.second ≠ e.third) (alice : Triple) (g : Variable → Bool) (slot : Fin 3) : slotPredicate e alice g slot ↔ questionPredicate e (nameAt e (slotOfFin slot)) alice (g (nameAt e (slotOfFin slot))) := by exact (question_predicate_at_slot e h12 h13 h23 alice _ (slotOfFin slot)).symm
theorem sum_slot_acceptance (e : Equation Variable) (alice : Triple) (g : Variable → Bool) : ∑ slot : Fin 3, slotAcceptance e alice g slot = (acceptedSlots alice (bobTriple g e) e.rhs : ℚ) := by rw [Fin.sum_univ_three] by_cases valid : parity alice = e.rhs · simp only [slotAcceptance, slotPredicate, valid, true_and, slotOfFin, show (1 : Fin 3) ≠ 0 from by decide, show (2 : Fin 3) ≠ 0 from by decide, show (2 : Fin 3) ≠ 1 from by decide, ↓reduceIte, nameAt, bitAt, acceptedSlots, matchingSlots, bobTriple, Nat.cast_add] split_ifs <;> simp_all · simp [slotAcceptance, slotPredicate, valid, acceptedSlots]
theorem expect_slot_acceptance (e : Equation Variable) (alice : Triple) (g : Variable → Bool) : Finset.univ.expect (slotAcceptance e alice g) = (acceptedSlots alice (bobTriple g e) e.rhs : ℚ) / 3 := by rw [Fintype.expect_eq_sum_div_card, sum_slot_acceptance] simp
variable [Fintype Index]
def acceptanceProbability (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) : ℚ := Finset.univ.expect (fun q : Index × Fin 3 => slotAcceptance (equations q.1) (alice q.1) g q.2)
def failureProbability (equations : Index → Equation Variable) (g : Variable → Bool) : ℚ := Finset.univ.expect (fun i : Index => (failedEquation (bobTriple g (equations i)) (equations i).rhs : ℚ))
theorem acceptance_probability_eq_expected_count (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) : acceptanceProbability equations alice g = Finset.univ.expect (fun i : Index => (acceptedSlots (alice i) (bobTriple g (equations i)) (equations i).rhs : ℚ) / 3) := by unfold acceptanceProbability rw [← Finset.univ_product_univ, Finset.expect_product] exact Finset.expect_congr rfl (fun i _ => expect_slot_acceptance (equations i) (alice i) g)
theorem acceptance_probability_nonnegative (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) : 0 ≤ acceptanceProbability equations alice g := by apply Finset.expect_nonneg intro q _ unfold slotAcceptance split <;> norm_num
theorem acceptance_probability_le_one [Nonempty Index] (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) : acceptanceProbability equations alice g ≤ 1 := by apply Finset.expect_le Finset.univ_nonempty intro q _ unfold slotAcceptance split <;> norm_num
theorem acceptance_plus_failure_third_le_one [Nonempty Index] (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) : acceptanceProbability equations alice g + failureProbability equations g / 3 ≤ 1 := by rw [acceptance_probability_eq_expected_count] unfold failureProbability rw [Finset.expect_div, ← Finset.expect_add_distrib] apply Finset.expect_le Finset.univ_nonempty intro i _ have h : (acceptedSlots (alice i) (bobTriple g (equations i)) (equations i).rhs : ℚ) + (failedEquation (bobTriple g (equations i)) (equations i).rhs : ℚ) ≤ 3 := by exact_mod_cast local_count_bound (alice i) (bobTriple g (equations i)) (equations i).rhs linarith
theorem deterministic_soundness [Nonempty Index] (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) (gap : (1 : ℚ) / 64 ≤ failureProbability equations g) : acceptanceProbability equations alice g ≤ (191 : ℚ) / 192 := by have h := acceptance_plus_failure_third_le_one equations alice g linarith
theorem failureCount_eq_countP (equations : I → Equation Variable) (g : Variable → Bool) (xs : List I) : failureCount equations g xs = xs.countP (fun i => decide (parity (bobTriple g (equations i)) ≠ (equations i).rhs)) := by induction xs with | nil => rfl | cons i xs ih => simp only [failureCount, List.countP_cons, ih] by_cases h : parity (bobTriple g (equations i)) = (equations i).rhs · simp [failedEquation, h] · simp [failedEquation, h, Nat.add_comm]
theorem failure_count_finRange_eq_count_ofFn {n : Nat} (equations : Fin n → Equation Variable) (g : Variable → Bool) : failureCount equations g (List.finRange n) = (List.ofFn (fun i => decide (parity (bobTriple g (equations i)) ≠ (equations i).rhs))).countP id := by rw [failureCount_eq_countP] have h := List.countP_map (l := List.finRange n) (f := fun i => decide (parity (bobTriple g (equations i)) ≠ (equations i).rhs)) (p := id) simpa only [List.finRange, List.map_ofFn, Function.comp_def, id_eq] using h.symm
theorem failure_probability_eq_count_finRange {n : Nat} (equations : Fin n → Equation Variable) (g : Variable → Bool) : failureProbability equations g = (failureCount equations g (List.finRange n) : ℚ) / n := by rw [failure_count_finRange_eq_count_ofFn] rw [← expect_bool_indicator_eq_count_ofFn] apply Finset.expect_congr rfl intro i _ by_cases h : parity (bobTriple g (equations i)) = (equations i).rhs · simp [failedEquation, h] · simp [failedEquation, h]
theorem failure_gap_of_count_gap {n : Nat} (nonempty : 0 < n) (equations : Fin n → Equation Variable) (g : Variable → Bool) (gap : n ≤ 64 * failureCount equations g (List.finRange n)) : (1 : ℚ) / 64 ≤ failureProbability equations g := by rw [failure_probability_eq_count_finRange] have hn : (0 : ℚ) < n := by exact_mod_cast nonempty rw [le_div_iff₀ hn] have hg : (n : ℚ) ≤ 64 * (failureCount equations g (List.finRange n) : ℚ) := by exact_mod_cast gap linarith
theorem soundness_from_count_gap {n : Nat} (nonempty : 0 < n) (equations : Fin n → Equation Variable) (alice : Fin n → Triple) (g : Variable → Bool) (gap : n ≤ 64 * failureCount equations g (List.finRange n)) : acceptanceProbability equations alice g ≤ (191 : ℚ) / 192 := by have : Nonempty (Fin n) := ⟨⟨0, nonempty⟩⟩ exact deterministic_soundness equations alice g (failure_gap_of_count_gap nonempty equations g gap)
def randomizedAcceptance [Fintype Coin] (equations : Index → Equation Variable) (weight : Coin → ℚ) (alice : Coin → Index → Triple) (bob : Coin → Variable → Bool) : ℚ := ∑ c, weight c * acceptanceProbability equations (alice c) (bob c)
theorem randomized_soundness [Nonempty Index] [Fintype Coin] (equations : Index → Equation Variable) (gap : ∀ g : Variable → Bool, (1 : ℚ) / 64 ≤ failureProbability equations g) (weight : Coin → ℚ) (weight_nonnegative : ∀ c, 0 ≤ weight c) (weight_sum : ∑ c, weight c = 1) (alice : Coin → Index → Triple) (bob : Coin → Variable → Bool) : randomizedAcceptance equations weight alice bob ≤ (191 : ℚ) / 192 := by calc randomizedAcceptance equations weight alice bob ≤ ∑ c, weight c * ((191 : ℚ) / 192) := by apply Finset.sum_le_sum intro c _ exact mul_le_mul_of_nonneg_left (deterministic_soundness equations (alice c) (bob c) (gap (bob c))) (weight_nonnegative c) _ = (191 : ℚ) / 192 := by rw [← Finset.sum_mul, weight_sum, one_mul]
instance tripleFintype : Fintype Triple := Fintype.ofEquiv (Bool × Bool × Bool) { toFun := fun t => ⟨t.1, t.2.1, t.2.2⟩ invFun := fun t => (t.first, t.second, t.third) left_inv := fun _ => rfl right_inv := fun _ => rfl }
instance tripleInhabited : Inhabited Triple := ⟨⟨false, false, false⟩⟩
noncomputable def deterministicValue [Fintype Variable] (equations : Index → Equation Variable) : ℚ := by classical exact Finset.univ.sup' Finset.univ_nonempty (fun s : (Index → Triple) × (Variable → Bool) => acceptanceProbability equations s.1 s.2)
theorem acceptance_le_value [Fintype Variable] (equations : Index → Equation Variable) (alice : Index → Triple) (g : Variable → Bool) : acceptanceProbability equations alice g ≤ deterministicValue equations := by classical exact Finset.le_sup' (fun s : (Index → Triple) × (Variable → Bool) => acceptanceProbability equations s.1 s.2) (Finset.mem_univ (alice, g))
theorem value_attained [Fintype Variable] (equations : Index → Equation Variable) : ∃ (alice : Index → Triple) (g : Variable → Bool), acceptanceProbability equations alice g = deterministicValue equations := by classical obtain ⟨s, _, hs⟩ := Finset.exists_mem_eq_sup' Finset.univ_nonempty (fun s : (Index → Triple) × (Variable → Bool) => acceptanceProbability equations s.1 s.2) exact ⟨s.1, s.2, hs.symm⟩
theorem value_soundness [Nonempty Index] [Fintype Variable] (equations : Index → Equation Variable) (gap : ∀ g : Variable → Bool, (1 : ℚ) / 64 ≤ failureProbability equations g) : deterministicValue equations ≤ (191 : ℚ) / 192 := by classical apply Finset.sup'_le intro s _ exact deterministic_soundness equations s.1 s.2 (gap s.2)
theorem randomized_acceptance_le_value [Fintype Variable] [Fintype Coin] (equations : Index → Equation Variable) (weight : Coin → ℚ) (weight_nonnegative : ∀ c, 0 ≤ weight c) (weight_sum : ∑ c, weight c = 1) (alice : Coin → Index → Triple) (bob : Coin → Variable → Bool) : randomizedAcceptance equations weight alice bob ≤ deterministicValue equations := by calc randomizedAcceptance equations weight alice bob ≤ ∑ c, weight c * deterministicValue equations := by apply Finset.sum_le_sum intro c _ exact mul_le_mul_of_nonneg_left (acceptance_le_value equations (alice c) (bob c)) (weight_nonnegative c) _ = deterministicValue equations := by rw [← Finset.sum_mul, weight_sum, one_mul]
theorem randomized_value_attained [Fintype Variable] [Fintype Coin] (equations : Index → Equation Variable) (weight : Coin → ℚ) (weight_sum : ∑ c, weight c = 1) : ∃ (alice : Coin → Index → Triple) (bob : Coin → Variable → Bool), randomizedAcceptance equations weight alice bob = deterministicValue equations := by obtain ⟨alice, bob, h⟩ := value_attained equations refine ⟨fun _ => alice, fun _ => bob, ?_⟩ simp only [randomizedAcceptance, h, ← Finset.sum_mul, weight_sum, one_mul]
theorem cloned_failure_probability_gap (s : ActualSource.Source) (source_gap : ∀ A : Fin s.«variables» → Bool, s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !CloneGap.satisfied e A)) (g : FiniteSource.Name s → Bool) : (1 : ℚ) / 64 ≤ failureProbability (FiniteSource.incidenceEquation s) g := by apply failure_gap_of_count_gap (FiniteSource.clonedSource_nonempty s) simpa only [FiniteSource.occurrences, List.length_finRange] using FiniteSource.incidence_failure_gap s source_gap g
theorem cloned_value_soundness (s : ActualSource.Source) (source_gap : ∀ A : Fin s.«variables» → Bool, s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !CloneGap.satisfied e A)) : deterministicValue (FiniteSource.incidenceEquation s) ≤ (191 : ℚ) / 192 := by exact value_soundness _ (cloned_failure_probability_gap s source_gap)
theorem cloned_randomized_soundness [Fintype Coin] (s : ActualSource.Source) (source_gap : ∀ A : Fin s.«variables» → Bool, s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !CloneGap.satisfied e A)) (weight : Coin → ℚ) (weight_nonnegative : ∀ c, 0 ≤ weight c) (weight_sum : ∑ c, weight c = 1) (alice : Coin → FiniteSource.Occurrence s → Triple) (bob : Coin → FiniteSource.Name s → Bool) : randomizedAcceptance (FiniteSource.incidenceEquation s) weight alice bob ≤ (191 : ℚ) / 192 := by exact randomized_soundness _ (cloned_failure_probability_gap s source_gap) weight weight_nonnegative weight_sum alice bob
namespace FoundationBridge
variable {Variable Index I : Type} [Fintype Index]
open MinUncutGames.Foundations.Gamesopen MinUncutGames.Soundness.IncidenceExtraction (Incidence)
noncomputable def uniformDistribution (Ω : Type*) [Fintype Ω] [Nonempty Ω] : FiniteDistribution Ω where weight _ := (Fintype.card Ω : ℝ)⁻¹ nonnegative _ := inv_nonneg.mpr (Nat.cast_nonneg _) normalized := by have h : (Fintype.card Ω : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero simp [h]
theorem uniform_probability_eq_rat_expect {Ω : Type*} [Fintype Ω] [Nonempty Ω] (event : Ω → Bool) : (uniformDistribution Ω).probability event = ((Finset.univ.expect (fun x => if event x then (1 : ℚ) else 0) : ℚ) : ℝ) := by unfold FiniteDistribution.probability uniformDistribution rw [Fintype.expect_eq_sum_div_card] push_cast rw [div_eq_mul_inv, Finset.sum_mul] apply Finset.sum_congr rfl intro x _ cases event x <;> simp
def functionalTriple (a : Fin 3 → Bool) : Triple := ⟨a 0, a 1, a 2⟩
theorem functionalTriple_bitAt (a : Fin 3 → Bool) (i : Fin 3) : bitAt (functionalTriple a) (slotOfFin i) = a i := by fin_cases i <;> simp [functionalTriple, slotOfFin, bitAt]
def extractionIncidence (equations : I → Equation Variable) : MinUncutGames.Soundness.IncidenceExtraction.Incidence I Variable where name o i := nameAt (equations o) (slotOfFin i) rhs o := (equations o).rhs
def DistinctNames (equations : I → Equation Variable) : Prop := ∀ o, (equations o).first ≠ (equations o).second ∧ (equations o).first ≠ (equations o).third ∧ (equations o).second ≠ (equations o).third
theorem extraction_names_injective (equations : I → Equation Variable) (distinct : DistinctNames equations) : ∀ o i j, (extractionIncidence equations).name o i = (extractionIncidence equations).name o j → i = j := by intro o i j obtain ⟨h12, h13, h23⟩ := distinct o have h21 := Ne.symm h12 have h31 := Ne.symm h13 have h32 := Ne.symm h23 fin_cases i <;> fin_cases j <;> simp_all [extractionIncidence, slotOfFin, nameAt]
noncomputable def foundationGame [Nonempty Index] [Fintype Variable] (equations : Index → Equation Variable) : Game Index Variable (Fin 3 → Bool) Bool := by classical exact { questions := (uniformDistribution (Index × Fin 3)).pushforward (fun q => (q.1, (extractionIncidence equations).name q.1 q.2)) accepts := fun o name a b => decide ((extractionIncidence equations).namedAccepts o name a b) }
theorem foundation_success_eq_rat_acceptance [Nonempty Index] [Fintype Variable] (equations : Index → Equation Variable) (distinct : DistinctNames equations) (alice : Index → Fin 3 → Bool) (bob : Variable → Bool) : (foundationGame equations).success (alice, bob) = (acceptanceProbability equations (fun o => functionalTriple (alice o)) bob : ℝ) := by classical have hRat : Finset.univ.expect (fun q : Index × Fin 3 => if (extractionIncidence equations).namedAccepts q.1 ((extractionIncidence equations).name q.1 q.2) (alice q.1) (bob ((extractionIncidence equations).name q.1 q.2)) then (1 : ℚ) else 0) = acceptanceProbability equations (fun o => functionalTriple (alice o)) bob := by apply Finset.expect_congr rfl intro q _ have heq : (extractionIncidence equations).namedAccepts q.1 ((extractionIncidence equations).name q.1 q.2) (alice q.1) (bob ((extractionIncidence equations).name q.1 q.2)) ↔ slotPredicate (equations q.1) (functionalTriple (alice q.1)) bob q.2 := by rw [MinUncutGames.Soundness.IncidenceExtraction.Incidence.namedAccepts_iff_accepts _ (extraction_names_injective equations distinct)] simp only [MinUncutGames.Soundness.IncidenceExtraction.Incidence.accepts, slotPredicate, functionalTriple_bitAt] rfl by_cases h : slotPredicate (equations q.1) (functionalTriple (alice q.1)) bob q.2 · simp only [slotAcceptance, ite_eq_left h, ite_eq_left (heq.mpr h)] · have hn := fun hn => h (heq.mp hn) simp only [slotAcceptance, ite_eq_right h, ite_eq_right hn] unfold Game.success foundationGame rw [FiniteDistribution.probability_pushforward, uniform_probability_eq_rat_expect] simpa only [Game.wins, decide_eq_true_eq] using congrArg (fun x : ℚ => (x : ℝ)) hRat
theorem foundation_value_soundness [Nonempty Index] [Fintype Variable] (equations : Index → Equation Variable) (distinct : DistinctNames equations) (gap : ∀ g : Variable → Bool, (1 : ℚ) / 64 ≤ failureProbability equations g) : (foundationGame equations).value ≤ (191 : ℝ) / 192 := by apply (Game.value_le_iff _ _).2 intro strategy rw [foundation_success_eq_rat_acceptance equations distinct] have h := (Rat.cast_le (K := ℝ)).mpr (deterministic_soundness equations (fun o => functionalTriple (strategy.1 o)) strategy.2 (gap strategy.2)) norm_num at h ⊢ exact h
theorem foundation_value_le_one_sub_gap_third [Nonempty Index] [Fintype Variable] (equations : Index → Equation Variable) (distinct : DistinctNames equations) (epsilon : ℝ) (gap : ∀ g : Variable → Bool, epsilon ≤ (failureProbability equations g : ℝ)) : (foundationGame equations).value ≤ 1 - epsilon / 3 := by apply (Game.value_le_iff _ _).2 intro strategy rw [foundation_success_eq_rat_acceptance equations distinct] have h := (Rat.cast_le (K := ℝ)).mpr (acceptance_plus_failure_third_le_one equations (fun o => functionalTriple (strategy.1 o)) strategy.2) push_cast at h linarith [gap strategy.2]
def sourceEquation (s : ActualSource.Source) : Fin s.occurrences → Equation (Fin s.«variables») := fun i => SourceIncidence.toIncidence (s.equation i)
noncomputable def sourceGame (s : ActualSource.Source) : Game (Fin s.occurrences) (Fin s.«variables») (Fin 3 → Bool) Bool := foundationGame (sourceEquation s)
theorem source_failure_probability (s : ActualSource.Source) (g : Fin s.«variables» → Bool) : failureProbability (sourceEquation s) g = s.failure g := by unfold failureProbability ActualSource.Source.failure apply Finset.expect_congr rfl intro i _ simp only [sourceEquation, SourceIncidence.failedEquation_eq, ActualSource.Source.satisfied] by_cases h : CloneGap.satisfied (s.equation i) g = true <;> simp [h]
theorem source_value_le_one_sub_gap_third (s : ActualSource.Source) (distinct : s.DistinctNames) (epsilon : ℝ) (gap : ∀ g : Fin s.«variables» → Bool, epsilon ≤ (s.failure g : ℝ)) : (sourceGame s).value ≤ 1 - epsilon / 3 := by apply foundation_value_le_one_sub_gap_third (sourceEquation s) distinct epsilon intro g rw [source_failure_probability] exact gap g
theorem cloned_foundation_value_soundness (s : ActualSource.Source) (source_gap : ∀ A : Fin s.«variables» → Bool, s.sourceList.length ≤ 4 * s.sourceList.countP (fun e => !CloneGap.satisfied e A)) : (foundationGame (FiniteSource.incidenceEquation s)).value ≤ (191 : ℝ) / 192 := by apply foundation_value_soundness _ _ (cloned_failure_probability_gap s source_gap) intro o exact FiniteSource.names_distinct s o
end FoundationBridge
end MinUncutGames.Reduction.IncidenceProbability
endsectionnamespace MinUncutGames.Reduction.SourceProbability
open ActualSource
theorem Source_failure_eq_count (S : Source) (A : Fin S.«variables» → Bool) : S.failure A = (S.sourceList.countP (fun e => !CloneGap.satisfied e A) : ℚ) / S.occurrences := by have hp := IncidenceProbability.expect_bool_indicator_eq_count_ofFn (fun i : Fin S.occurrences => !S.satisfied A i) have he : Finset.univ.expect (fun i : Fin S.occurrences => if !S.satisfied A i then (1 : ℚ) else 0) = S.failure A := by unfold Source.failure congr 1 funext i cases S.satisfied A i <;> rfl rw [he] at hp rw [hp] congr 2 have hmap : List.ofFn (fun i : Fin S.occurrences => !S.satisfied A i) = S.sourceList.map (fun e => !CloneGap.satisfied e A) := by simp only [Source.sourceList, List.map_ofFn, Source.satisfied, Function.comp_def] rw [hmap, List.countP_map] rfl
theorem ofList_failure {n : Nat} (es : List (CloneGap.Equation (Fin n))) (hne : es ≠ []) (A : Fin n → Bool) : (Source.ofList es hne).failure A = (es.countP (fun e => !CloneGap.satisfied e A) : ℚ) / es.length := by have h := Source_failure_eq_count (Source.ofList es hne) A simpa [Source.sourceList, Source.ofList] using h
theorem count_complement {α : Type*} (es : List α) (p : α → Bool) : es.countP (fun e => !p e) + es.countP p = es.length := by induction es with | nil => simp | cons e es ih => cases hp : p e <;> simp [hp] at * <;> omega
theorem failure_add_satisfaction (S : Source) (A : Fin S.«variables» → Bool) : S.failure A + (S.sourceList.countP (fun e => CloneGap.satisfied e A) : ℚ) / S.occurrences = 1 := by rw [Source_failure_eq_count, ← add_div] have h := count_complement S.sourceList (fun e => CloneGap.satisfied e A) have hc : ((S.sourceList.countP (fun e => !CloneGap.satisfied e A) : ℚ) + (S.sourceList.countP (fun e => CloneGap.satisfied e A) : ℚ)) = S.occurrences := by exact_mod_cast (h.trans S.sourceList_length) rw [hc, div_self] exact_mod_cast Nat.ne_of_gt S.nonempty
theorem quarter_gap_iff (S : Source) (A : Fin S.«variables» → Bool) : (1 / 4 : ℚ) ≤ S.failure A ↔ S.sourceList.length ≤ 4 * S.sourceList.countP (fun e => !CloneGap.satisfied e A) := by rw [Source_failure_eq_count] have hn : (0 : ℚ) < S.occurrences := by exact_mod_cast S.nonempty rw [le_div_iff₀ hn] constructor · intro h have h' : (S.occurrences : ℚ) ≤ 4 * (S.sourceList.countP (fun e => !CloneGap.satisfied e A) : ℚ) := by linarith rw [S.sourceList_length] exact_mod_cast h' · intro h rw [S.sourceList_length] at h have h' : (S.occurrences : ℚ) ≤ 4 * (S.sourceList.countP (fun e => !CloneGap.satisfied e A) : ℚ) := by exact_mod_cast h linarith
end MinUncutGames.Reduction.SourceProbability
end
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import Mathlibimport OAI.Computability.MinUncut.PCP.Parity
namespace OAI
noncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Filteropen scoped Topology NNRealopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Polynomial Filteropen scoped BigOperators Topologyopen MeasureTheory ProbabilityTheory WithLpopen scoped BigOperators RealInnerProductSpacenamespace MinUncut.Inneropen MeasureTheory ProbabilityTheoryopen scoped BigOperatorsvariable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A]variable {m n : ℕ}
def jointCoefficient (f : FoldedProof A) (σ η : ℝ) (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ) : ℝ := BinaryFourier.coefficient (fun B => GaussianHermite.coeff (fun c => gradient f B σ η c x) I) α
def constantArray (k : Row m n → F₂) : FaceArray A m n := fun r => AffineMap.const F₂ A (k r)
omit [Fintype A] inlemma constantArray_add (B : FaceArray A m n) (k : Row m n → F₂) : constantArray k+B = addConstantArray B k := by funext r; exact add_comm _ _
lemma hermite_gradient_constantArray (f : FoldedProof A) (B : FaceArray A m n) (k : Row m n → F₂) {σ : ℝ} (hσ : σ ≠ 0) (η : ℝ) (x : Point m n) (I : Point m n → ℕ) : GaussianHermite.coeff (fun c => gradient f (constantArray k+B) σ η c x) I = BinaryFourier.sign ((rowCode k).val x + GaussianHermite.parity (rowCode k).val I) * GaussianHermite.coeff (fun c => gradient f B σ η c x) I := by simp only [constantArray_add, gradient_addConstantArray f B k hσ, GaussianHermite.coeff_const_mul, BinaryFourier.sign_add, mul_assoc] rw [GaussianHermite.coeff_diagonal (rowCode k).val (fun c => gradient f B σ η c x) I]
lemma sign_injective : Function.Injective BinaryFourier.sign := by intro a b hab have h : ∀ x : F₂, x=0 ∨ x=1 := by decide rcases h a with rfl | rfl · rcases h b with rfl | rfl · rfl · norm_num at hab · rcases h b with rfl | rfl · norm_num at hab · rfl
theorem joint_row_gauge (f : FoldedProof A) {σ : ℝ} (hσ : σ ≠ 0) (η : ℝ) (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ) (hne : jointCoefficient f σ η x α I ≠ 0) (k : Row m n → F₂) : α (constantArray k) = (rowCode k).val x + GaussianHermite.parity (rowCode k).val I := by have ht := BinaryFourier.coefficient_translate (fun B : FaceArray A m n => GaussianHermite.coeff (fun c => gradient f B σ η c x) I) α (constantArray k) simp only [hermite_gradient_constantArray f _ k hσ, BinaryFourier.coefficient, mul_assoc, ← Finset.mul_expect] at ht apply sign_injective change _ * jointCoefficient f σ η x α I = _ * jointCoefficient f σ η x α I at ht exact mul_right_cancel₀ hne ht.symm
theorem joint_cylinder_gauge (f : FoldedProof A) (σ η : ℝ) (x : Point m n) (α : Module.Dual F₂ (FaceArray A m n)) (I : Point m n → ℕ) (hne : jointCoefficient f σ η x α I ≠ 0) (i j : Fin m) (hij : i ≠ j) (q : Point m n) (a : Forms A) : α (cylinderArray i j q a) = 0 := by have ht := BinaryFourier.coefficient_translate (fun B : FaceArray A m n => GaussianHermite.coeff (fun c => gradient f B σ η c x) I) α (cylinderArray i j q a) have hg (B : FaceArray A m n) : gradient f (cylinderArray i j q a+B) σ η = gradient f B σ η := by rw [add_comm, gradient_cylinder f B i j hij] simp only [hg] at ht by_contra hn have hs : BinaryFourier.character α (cylinderArray i j q a) = -1 := by simp [BinaryFourier.character, BinaryFourier.sign, hn] rw [hs] at ht exact hne (by change jointCoefficient f σ η x α I = -1*jointCoefficient f σ η x α I at ht; linarith)end MinUncut.Inner
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import Mathlibimport OAI.Computability.MinUncut.Games.JointHintSamplingimport OAI.Computability.MinUncut.Estimates.PatchDensity
namespace OAI
noncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Inner OuterSmoothnessattribute [local instance] Classical.propDecidable BinaryFourier.dualFintypevariable {Name I : Type*} [Fintype I]
lemma raw_background_expect (U : I → Equation Name) {d : ℕ} (H : Finset I) (f : (Fin d → Forms (FirstAlphabet U)) → ℝ) : (𝔼 pos : I → Fin 3, 𝔼 L : Fin d → Forms (SecondAlphabet (secondQuestion U (hiddenSet H) pos)), f (fun k => formPullback (projection U (hiddenSet H) pos) (L k))) = (𝔼 z : (Fin d → F₂) × (I → JointForms.Raw d), f (firstHints U (hiddenSet H) (rawPositions z.2) (rawCoefficients z.1 z.2))) := by classical have hpos (pos : I → Fin 3) : (𝔼 L : Fin d → Forms (SecondAlphabet (secondQuestion U (hiddenSet H) pos)), f (fun k => formPullback (projection U (hiddenSet H) pos) (L k))) = (𝔼 c : HintCoefficients I d, f (firstHints U (hiddenSet H) pos c)) := (uniform_hintTupleGenerator _ d (fun L => f (fun k => formPullback (projection U (hiddenSet H) pos) (L k)))).symm simp_rw [hpos] rw [← expect_pair (fun z : (I → Fin 3) × HintCoefficients I d => f (firstHints U (hiddenSet H) z.1 z.2))] exact Fintype.expect_equiv (hintRawEquiv (I := I) d) _ _ (fun z => rfl)
lemma actual_joint_law (U : I → Equation Name) {d k : ℕ} (hk : k≤Fintype.card I) (f : (Fin d → Forms (FirstAlphabet U)) → ℝ) : let : Nonempty (FixedSets I k) := fixedSets_nonempty hk (𝔼 H : FixedSets I k,𝔼 pos : I → Fin 3, 𝔼 L : Fin d → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)), f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L j))) = (𝔼 sample : (Fin d → F₂) × (FixedSets I k × (I → JointForms.Raw d)), f (tupleCoordinateGenerator U d (JointForms.affineOutput (fun i => directionEmbedding (U i)) (fun i => (origin (U i)).val) sample))) := by classical let : Nonempty (FixedSets I k) := fixedSets_nonempty hk simp_rw [raw_background_expect] rw [expect_pair] simp_rw [expect_pair] rw [Finset.expect_comm] apply Finset.expect_congr rfl intro κ _ apply Finset.expect_congr rfl intro H _ apply Finset.expect_congr rfl intro w _ exact congrArg f (raw_joint_identity U H κ w)
theorem actual_joint_smoothness [Nonempty I] (U : I → Equation Name) {d k : ℕ} (hk : k≤Fintype.card I) (f : (Fin d → Forms (FirstAlphabet U)) → ℝ) {M : ℝ} (hM : 0≤M) (hf : ∀ L, |f L|≤M) : let : Nonempty (FixedSets I k) := fixedSets_nonempty hk |(𝔼 H : FixedSets I k,𝔼 pos : I → Fin 3, 𝔼 L : Fin d → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)), f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L j))) - (𝔼 L : Fin d → Forms (FirstAlphabet U), f L)| ≤ Real.sqrt (((2 : ℝ)^(4*d*k)-1)*(k : ℝ)^2/Fintype.card I)*M := by classical let : Nonempty (FixedSets I k) := fixedSets_nonempty hk rw [actual_joint_law U hk] let output := JointForms.affineOutput (fun i => directionEmbedding (U i)) (fun i => (origin (U i)).val) (d := d) (k := k) have h := Density.expect_difference (Density.ofMap output) (fun z => f (tupleCoordinateGenerator U d z)) hM (fun z => hf _) rw [Density.expect_ofMap,uniform_tupleCoordinateGenerator] at h have htv := JointForms.joint_smoothness hk (fun i => alphabet_dimension_le (U i)) (fun i => directionEmbedding (U i)) (fun i => directionEmbedding_injective (U i)) (fun i => (origin (U i)).val) (d := d) refine h.trans ?_ calc _ ≤ 2 * (Real.sqrt (((2 : ℝ)^(4*d*k)-1)*(k : ℝ)^2/Fintype.card I)/2)*M := by gcongr convert htv using 1 exact Density.tv_ofMap_instances _ _ _ _ _ _ _ _ output _ = _ := by ring
end MinUncut.Outer
namespace MinUncut.Outeropen MinUncut.Inner OuterSmoothnessattribute [local instance] Classical.propDecidable BinaryFourier.dualFintype
lemma expect_reindex {J K A : Type*} [Fintype J] [Fintype K] [Fintype A] [DecidableEq J] [DecidableEq K] (e : J ≃ K) (f : (J → A) → ℝ) : (𝔼 L : K → A, f (fun j => L (e j))) = 𝔼 L : J → A, f L := by exact Fintype.expect_equiv (Equiv.arrowCongr e.symm (Equiv.refl A)) _ _ (fun _ => rfl)
variable {Name I J : Type*} [Fintype I] [Fintype J] [DecidableEq J]
lemma pulled_background_reindex {K : Type*} [Fintype K] [DecidableEq K] (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3) (e : J ≃ K) (f : (J → Forms (FirstAlphabet U)) → ℝ) : (𝔼 L : K → Forms (SecondAlphabet (secondQuestion U hidden pos)), f (fun j => formPullback (projection U hidden pos) (L (e j)))) = 𝔼 L : J → Forms (SecondAlphabet (secondQuestion U hidden pos)), f (fun j => formPullback (projection U hidden pos) (L j)) := expect_reindex e (fun L => f (fun j => formPullback (projection U hidden pos) (L j)))
lemma actual_background_reindex {K : Type*} [Fintype K] [DecidableEq K] (U : I → Equation Name) (k : ℕ) (e : J ≃ K) (f : (J → Forms (FirstAlphabet U)) → ℝ) : (𝔼 H : FixedSets I k, 𝔼 pos : I → Fin 3, 𝔼 L : K → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)), f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L (e j)))) = 𝔼 H : FixedSets I k, 𝔼 pos : I → Fin 3, 𝔼 L : J → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)), f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L j)) := by apply Finset.expect_congr rfl intro H _ exact Finset.expect_congr rfl (fun pos _ => pulled_background_reindex U _ pos e f)
theorem actual_joint_smoothness_index [Nonempty I] (U : I → Equation Name) {k : ℕ} (hk : k≤Fintype.card I) (f : (J → Forms (FirstAlphabet U)) → ℝ) {M : ℝ} (hM : 0≤M) (hf : ∀ L, |f L|≤M) : let : Nonempty (FixedSets I k) := fixedSets_nonempty hk |(𝔼 H : FixedSets I k,𝔼 pos : I → Fin 3, 𝔼 L : J → Forms (SecondAlphabet (secondQuestion U (hiddenSet H.val) pos)), f (fun j => formPullback (projection U (hiddenSet H.val) pos) (L j))) - (𝔼 L : J → Forms (FirstAlphabet U), f L)| ≤ Real.sqrt (((2 : ℝ)^(4*Fintype.card J*k)-1)*(k : ℝ)^2/Fintype.card I)*M := by let : Nonempty (FixedSets I k) := fixedSets_nonempty hk let e := Fintype.equivFin J have h := actual_joint_smoothness (d := Fintype.card J) U hk (fun L => f (fun j => L (e j))) hM (fun L => hf _) dsimp only at h rw [actual_background_reindex U k e f,expect_reindex e f] at h exact h
end MinUncut.Outer
end
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import Mathlibimport OAI.Computability.MinUncut.Estimates.ListDecoding
namespace OAI
sectionnoncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Inner OuterSmoothnessattribute [local instance] Classical.propDecidable BinaryFourier.dualFintypevariable {Name I : Type*} [Fintype I]
def hiddenSet (H : Finset I) : I → Bool := fun i => decide (i ∈ H)def rawPositions {d : ℕ} (w : I → JointForms.Raw d) : I → Fin 3 := fun i => (w i).1.1def rawCoefficients {d : ℕ} (κ : Fin d → F₂) (w : I → JointForms.Raw d) : HintCoefficients I d := fun k => (κ k,(fun i => (w i).1.2 k,fun i => (w i).2 k))
def hintRawEquiv (d : ℕ) : ((I → Fin 3) × HintCoefficients I d) ≃ ((Fin d → F₂) × (I → JointForms.Raw d)) where toFun z := (fun k => (z.2 k).1,fun i => ((z.1 i,fun k => (z.2 k).2.1 i), fun k => (z.2 k).2.2 i)) invFun z := (rawPositions z.2,rawCoefficients z.1 z.2) left_inv _ := rfl right_inv _ := rfl
lemma origin_coordinate_decomposition (E : Equation Name) (a : alphabet E) : a.val=directionEmbedding E ((alphabetCoordinates E).symm a)+(origin E).val := by exact congrArg Subtype.val ((alphabetCoordinates E).apply_symm_apply a) |>.symm
omit [Fintype I] inlemma raw_slot_expansion (U : I → Equation Name) {d : ℕ} (H : Finset I) (w : I → JointForms.Raw d) (a : FirstAlphabet U) (i : I) (k : Fin d) : (if i ∈ H then (w i).1.2 k*(a i).val (w i).1.1 else (w i).2 k (a i).val) = (JointForms.output (fun i => directionEmbedding (U i)) H w i k) ((alphabetCoordinates (U i)).symm (a i)) + (if i ∈ H then (w i).1.2 k*(origin (U i)).val (w i).1.1 else (w i).2 k (origin (U i)).val) := by classical by_cases hi : i ∈ H · simp only [hi,↓reduceIte,JointForms.output,JointForms.hiddenPull] change (w i).1.2 k*(a i).val (w i).1.1 = (w i).1.2 k*(directionEmbedding (U i) ((alphabetCoordinates (U i)).symm (a i))) (w i).1.1+_ rw [origin_coordinate_decomposition (U i) (a i)] simp only [Pi.add_apply,mul_add] · simp only [hi,↓reduceIte,JointForms.output,JointForms.fullPull, LinearMap.pi_apply,LinearMap.comp_apply,LinearMap.proj_apply,LinearMap.dualMap_apply] rw [origin_coordinate_decomposition (U i) (a i),map_add]
lemma raw_joint_identity (U : I → Equation Name) {d k : ℕ} (H : FixedSets I k) (κ : Fin d → F₂) (w : I → JointForms.Raw d) : firstHints U (hiddenSet H.val) (rawPositions w) (rawCoefficients κ w) = tupleCoordinateGenerator U d (JointForms.affineOutput (fun i => directionEmbedding (U i)) (fun i => (origin (U i)).val) (κ,H,w)) := by classical funext l apply AffineMap.ext intro a change formPullback (projection U (hiddenSet H.val) (rawPositions w)) (directHint _ (κ l) (fun i => (w i).1.2 l) (fun i => (w i).2 l)) a = firstFormCoordinates U (_,_) a rw [pulledHint_apply,firstFormCoordinates_apply] simp only [hiddenSet,decide_eq_true_eq,rawPositions] simp_rw [raw_slot_expansion U H.val w a] simp only [Finset.sum_add_distrib,JointForms.affineOutput,JointForms.offset,Pi.add_apply] ring
end MinUncut.Outer
endend
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208import Mathlibimport OAI.Computability.MinUncut.Estimates.SelectedProject
namespace OAI
noncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Filteropen scoped Topology NNRealopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Polynomial Filteropen scoped BigOperators Topologyopen MeasureTheory ProbabilityTheory WithLpopen scoped BigOperators RealInnerProductSpaceopen scoped BigOperatorsnamespace MinUncut.RowNoiseopen MeasureTheory ProbabilityTheory BinaryFourier GaussianHermiteopen scoped BigOperatorslocal instance jointInnerDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] : Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintypevariable {R W ι : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W] [AddCommGroup W] [Module F₂ W] [Fintype ι]
lemma maskProject_selfadjoint (S : Finset R) (f g : (R → W) → ℝ) : (𝔼 B, f B * maskProject S g B) = 𝔼 B, maskProject S f B * g B := by rw [← parseval_inner, ← parseval_inner] simp only [coefficient_maskProject] apply Finset.sum_congr rfl intro α _ split_ifs <;> ring
lemma maskProject_idempotent (S T : Finset R) (f : (R → W) → ℝ) (B : R → W) : maskProject S (maskProject T f) B = if S=T then maskProject S f B else 0 := by rw [maskProject_expansion] simp only [coefficient_maskProject] by_cases h : S=T · subst T simp only [↓reduceIte] rw [maskProject_expansion] apply Finset.sum_congr rfl intro α _ split_ifs <;> simp · rw [ite_eq_right h] apply Finset.sum_eq_zero intro α _ split_ifs with hS hT · exact (h (hS.symm.trans hT)).elim · simp · rfl
lemma maskProject_inner (S T : Finset R) (f g : (R → W) → ℝ) : (𝔼 B, maskProject S f B * maskProject T g B) = if S=T then (𝔼 B, f B * maskProject S g B) else 0 := by rw [← maskProject_selfadjoint] simp_rw [maskProject_idempotent] split_ifs with h · rfl · simp
omit [AddCommGroup W] [Module F₂ W] inlemma maskHermite_eq (S : Finset R) (I : ι → ℕ) (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) (c : ι → ℝ) : maskHermite S I u B c = psi I c * maskProject S (fun D => GaussianHermite.coeff (u D) I) B := by unfold maskHermite maskProject hermiteComponent GaussianHermite.coeff simp only [mul_left_comm _ (psi I c), ← Finset.mul_expect]
def jointInner (u v : (R → W) → (ι → ℝ) → ℝ) : ℝ := 𝔼 B, ∫ c, u B c * v B c ∂γpi ι
def jointEnergy (u : (R → W) → (ι → ℝ) → ℝ) : ℝ := 𝔼 B, ∫ c, (u B c)^2 ∂γpi ι
omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] inlemma jointEnergy_nonneg (u : (R → W) → (ι → ℝ) → ℝ) : 0 ≤ jointEnergy u := Finset.expect_nonneg (fun _ _ => integral_nonneg (fun _ => sq_nonneg _))
omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] inlemma jointInner_self (u : (R → W) → (ι → ℝ) → ℝ) : jointInner u u = jointEnergy u := by simp only [jointInner, jointEnergy, pow_two]
omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] inlemma jointInner_symm (u v : (R → W) → (ι → ℝ) → ℝ) : jointInner u v = jointInner v u := by simp only [jointInner, mul_comm]
lemma jointInner_maskHermite (S T : Finset R) (I J : ι → ℕ) (u v : (R → W) → (ι → ℝ) → ℝ) : jointInner (maskHermite S I u) (maskHermite T J v) = if I=J then if S=T then (𝔼 B, GaussianHermite.coeff (u B) I * maskProject S (fun D => GaussianHermite.coeff (v D) J) B) else 0 else 0 := by classical unfold jointInner simp only [maskHermite_eq] have h (B : R → W) : (∫ c, (psi I c * maskProject S (fun D => GaussianHermite.coeff (u D) I) B) * (psi J c * maskProject T (fun D => GaussianHermite.coeff (v D) J) B) ∂γpi ι) = (if I=J then 1 else 0) * (maskProject S (fun D => GaussianHermite.coeff (u D) I) B * maskProject T (fun D => GaussianHermite.coeff (v D) J) B) := by simp_rw [mul_mul_mul_comm (psi I _) _ (psi J _) _] rw [integral_mul_const, psi_product] simp_rw [h, ← Finset.mul_expect, maskProject_inner] split_ifs <;> simp_all
lemma jointInner_source_component (S : Finset R) (I : ι → ℕ) (u : (R → W) → (ι → ℝ) → ℝ) : jointInner u (maskHermite S I u) = jointEnergy (maskHermite S I u) := by rw [← jointInner_self, jointInner_maskHermite] simp only [↓reduceIte] unfold jointInner apply Finset.expect_congr rfl intro B _ simp only [maskHermite_eq, ← mul_assoc, integral_mul_const] congr 1 unfold GaussianHermite.coeff simp only [mul_comm]
lemma components_orthogonal (a b : Finset R × (ι → ℕ)) (hab : a ≠ b) (u : (R → W) → (ι → ℝ) → ℝ) : jointInner (maskHermite a.1 a.2 u) (maskHermite b.1 b.2 u) = 0 := by rw [jointInner_maskHermite] split_ifs with hI hS · exact (hab (Prod.ext hS hI)).elim · rfl · rfl
omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] inlemma jointInner_sum_right {T : Type*} (s : Finset T) (u : (R → W) → (ι → ℝ) → ℝ) (v : T → (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) (hv : ∀ t ∈ s, ∀ B, MemLp (v t B) 2 (γpi ι)) : jointInner u (fun B c => ∑ t ∈ s, v t B c) = ∑ t ∈ s, jointInner u (v t) := by unfold jointInner simp only [Finset.mul_sum] have hh (B) : (∫ c, ∑ t ∈ s, u B c * v t B c ∂γpi ι) = ∑ t ∈ s, ∫ c, u B c * v t B c ∂γpi ι := integral_finsetSum s (fun t ht => (hu B).integrable_mul (hv t ht B)) simp_rw [hh] rw [Finset.expect_sum_comm]
omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] inlemma jointInner_sum_left {T : Type*} (s : Finset T) (u : T → (R → W) → (ι → ℝ) → ℝ) (v : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ t ∈ s, ∀ B, MemLp (u t B) 2 (γpi ι)) (hv : ∀ B, MemLp (v B) 2 (γpi ι)) : jointInner (fun B c => ∑ t ∈ s, u t B c) v = ∑ t ∈ s, jointInner (u t) v := by rw [jointInner_symm, jointInner_sum_right s v u hv hu] exact Finset.sum_congr rfl (fun t _ => jointInner_symm _ _)
lemma selectedProject_source_inner (J : Finset (Finset R × (ι → ℕ))) (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) : jointInner u (selectedProject J u) = ∑ j ∈ J, jointEnergy (maskHermite j.1 j.2 u) := by change jointInner u (fun B c => ∑ j ∈ J, maskHermite j.1 j.2 u B c) = _ rw [jointInner_sum_right J u _ hu (fun j _ B => memLp_maskHermite _ _ _ B)] exact Finset.sum_congr rfl (fun j _ => jointInner_source_component j.1 j.2 u)
lemma selectedProject_energy (J : Finset (Finset R × (ι → ℕ))) (u : (R → W) → (ι → ℝ) → ℝ) : jointEnergy (selectedProject J u) = ∑ j ∈ J, jointEnergy (maskHermite j.1 j.2 u) := by classical rw [← jointInner_self] change jointInner (fun B c => ∑ j ∈ J, maskHermite j.1 j.2 u B c) (selectedProject J u) = _ rw [jointInner_sum_left J _ _ (fun j _ B => memLp_maskHermite _ _ _ B) (memLp_selectedProject J u)] apply Finset.sum_congr rfl intro j hj change jointInner (maskHermite j.1 j.2 u) (fun B c => ∑ k ∈ J, maskHermite k.1 k.2 u B c) = _ rw [jointInner_sum_right J _ _ (memLp_maskHermite _ _ _) (fun k _ B => memLp_maskHermite _ _ _ B)] rw [Finset.sum_eq_single j] · exact jointInner_self _ · intro k hk hkj exact components_orthogonal j k hkj.symm u · exact fun hjn => (hjn hj).elim
omit [DecidableEq W] [AddCommGroup W] [Module F₂ W] inlemma jointEnergy_sub (u v : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) (hv : ∀ B, MemLp (v B) 2 (γpi ι)) : jointEnergy (fun B c => u B c-v B c) = jointEnergy u - 2*jointInner u v + jointEnergy v := by have h (B) : (∫ c, (u B c-v B c)^2 ∂γpi ι) = (∫ c, (u B c)^2 ∂γpi ι) - 2*(∫ c, u B c*v B c ∂γpi ι) + ∫ c, (v B c)^2 ∂γpi ι := by simp only [sub_sq, mul_assoc] have huv : Integrable (fun c => 2*(u B c*v B c)) (γpi ι) := ((hu B).integrable_mul (hv B)).const_mul 2 have hsub : Integrable (fun c => (u B c)^2-2*(u B c*v B c)) (γpi ι) := (hu B).integrable_sq.sub huv rw [integral_add hsub (hv B).integrable_sq, integral_sub (hu B).integrable_sq huv, integral_const_mul] simp only [jointEnergy, jointInner, h, Finset.expect_add_distrib, Finset.expect_sub_distrib, ← Finset.mul_expect]
theorem selectedProject_energy_le (J : Finset (Finset R × (ι → ℕ))) (u : (R → W) → (ι → ℝ) → ℝ) (hu : ∀ B, MemLp (u B) 2 (γpi ι)) : jointEnergy (selectedProject J u) ≤ jointEnergy u := by have h := jointEnergy_nonneg (fun B c => u B c-selectedProject J u B c) rw [jointEnergy_sub u _ hu (memLp_selectedProject J u), selectedProject_source_inner J u hu, ← selectedProject_energy] at h linarith
omit [AddCommGroup W] [Module F₂ W] inlemma selectedProject_sdiff (J K : Finset (Finset R × (ι → ℕ))) (hK : K ⊆ J) (u : (R → W) → (ι → ℝ) → ℝ) (B : R → W) (c : ι → ℝ) : selectedProject J u B c-selectedProject K u B c = selectedProject (J\K) u B c := by classical unfold selectedProject have h := Finset.sum_sdiff hK (f := fun j => maskHermite j.1 j.2 u B c) linarith
lemma selectedProject_loss_energy (J K : Finset (Finset R × (ι → ℕ))) (hK : K ⊆ J) (u : (R → W) → (ι → ℝ) → ℝ) : jointEnergy (fun B c => selectedProject J u B c-selectedProject K u B c) = ∑ j ∈ J\K, jointEnergy (maskHermite j.1 j.2 u) := by simp_rw [selectedProject_sdiff J K hK] exact selectedProject_energy _ uend MinUncut.RowNoise
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208import Mathlibimport OAI.Computability.MinUncut.Games.OuterQuestions
namespace OAI
namespace MinUncutGames.Foundations.Games
open scoped BigOperatorsnoncomputable section
namespace FiniteDistribution
theorem pushforward_eq_of_agree_on_support {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] (μ : FiniteDistribution Ω) (f g : Ω → Γ) (h : ∀ x, μ.weight x ≠ 0 → f x = g x) : μ.pushforward f = μ.pushforward g := by classical apply eq_of_weight_eq intro y simp only [pushforward] apply Finset.sum_congr rfl intro x _ by_cases hx : μ.weight x = 0 · simp [hx] · rw [h x hx]
theorem product_pushforward {Ω Γ A B : Type*} [Fintype Ω] [Fintype Γ] [Fintype A] [Fintype B] (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ) (f : Ω → A) (g : Γ → B) : (μ.product ν).pushforward (fun z => (f z.1, g z.2)) = (μ.pushforward f).product (ν.pushforward g) := by classical apply eq_of_weight_eq rintro ⟨a, b⟩ simp only [pushforward, product] rw [Fintype.sum_prod_type, Finset.sum_mul_sum] apply Finset.sum_congr rfl intro x _ apply Finset.sum_congr rfl intro y _ by_cases hx : f x = a <;> by_cases hy : g y = b <;> simp [hx, hy]
theorem table_row_weight_ne_zero {Q A : Type*} [Fintype Q] [Fintype A] [DecidableEq Q] (responses : Q → FiniteDistribution A) (answers : Q → A) (h : (table responses).weight answers ≠ 0) (q : Q) : (responses q).weight (answers q) ≠ 0 := by intro hq apply h change (∏ r, (responses r).weight (answers r)) = 0 exact Finset.prod_eq_zero (Finset.mem_univ q) hq
theorem table_repair_pushforward {Q A : Type*} [Fintype Q] [Fintype A] [DecidableEq Q] (responses : Q → FiniteDistribution A) (repair : Q → A → A) (hrepair : ∀ q a, (responses q).weight a ≠ 0 → repair q a = a) (q : Q) : (table responses).pushforward (fun answers => repair q (answers q)) = responses q := by calc _ = (table responses).pushforward (fun answers => answers q) := by apply pushforward_eq_of_agree_on_support intro answers h exact hrepair q (answers q) (table_row_weight_ne_zero responses answers h q) _ = responses q := table_eval_pushforward responses q
end FiniteDistribution
namespace KernelSampling
abbrev Seed (Q₁ Q₂ A B : Type*) := (Q₁ → A) × (Q₂ → B)
def readLeft {Q₁ Q₂ A B : Type*} (seed : Seed Q₁ Q₂ A B) (q : Q₁) : A := seed.1 qdef readRight {Q₁ Q₂ A B : Type*} (seed : Seed Q₁ Q₂ A B) (q : Q₂) : B := seed.2 q
def seedLaw {Q₁ Q₂ A B : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype A] [Fintype B] [DecidableEq Q₁] [DecidableEq Q₂] (left : Q₁ → FiniteDistribution A) (right : Q₂ → FiniteDistribution B) : FiniteDistribution (Seed Q₁ Q₂ A B) := (FiniteDistribution.table left).product (FiniteDistribution.table right)
theorem read_joint_pushforward {Q₁ Q₂ A B : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype A] [Fintype B] [DecidableEq Q₁] [DecidableEq Q₂] (left : Q₁ → FiniteDistribution A) (right : Q₂ → FiniteDistribution B) (x : Q₁) (y : Q₂) : (seedLaw left right).pushforward (fun seed => (readLeft seed x, readRight seed y)) = (left x).product (right y) := by unfold seedLaw readLeft readRight rw [FiniteDistribution.product_pushforward (FiniteDistribution.table left) (FiniteDistribution.table right) (fun answers => answers x) (fun answers => answers y), FiniteDistribution.table_eval_pushforward, FiniteDistribution.table_eval_pushforward]
theorem repaired_joint_pushforward {Q₁ Q₂ A B : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype A] [Fintype B] [DecidableEq Q₁] [DecidableEq Q₂] (left : Q₁ → FiniteDistribution A) (right : Q₂ → FiniteDistribution B) (repairLeft : Q₁ → A → A) (repairRight : Q₂ → B → B) (hleft : ∀ x a, (left x).weight a ≠ 0 → repairLeft x a = a) (hright : ∀ y b, (right y).weight b ≠ 0 → repairRight y b = b) (x : Q₁) (y : Q₂) : (seedLaw left right).pushforward (fun seed => (repairLeft x (readLeft seed x), repairRight y (readRight seed y))) = (left x).product (right y) := by unfold seedLaw readLeft readRight rw [FiniteDistribution.product_pushforward (FiniteDistribution.table left) (FiniteDistribution.table right) (fun answers => repairLeft x (answers x)) (fun answers => repairRight y (answers y)), FiniteDistribution.table_repair_pushforward left repairLeft hleft, FiniteDistribution.table_repair_pushforward right repairRight hright]
variable {I A B S : Type*} [DecidableEq I]
def completedLeft (j : I) (seed : Seed (A × S) (B × S) (I → A) (I → B)) (q : A × S) : I → A := Function.update (readLeft seed q) j q.1
def completedRight (j : I) (seed : Seed (A × S) (B × S) (I → A) (I → B)) (q : B × S) : I → B := Function.update (readRight seed q) j q.1
@[simp] theorem completedLeft_coordinate (j : I) (seed : Seed (A × S) (B × S) (I → A) (I → B)) (q : A × S) : completedLeft j seed q j = q.1 := by simp [completedLeft]
@[simp] theorem completedRight_coordinate (j : I) (seed : Seed (A × S) (B × S) (I → A) (I → B)) (q : B × S) : completedRight j seed q j = q.1 := by simp [completedRight]
private theorem update_eq_of_coordinate (xs : I → A) (j : I) (a : A) (h : xs j = a) : Function.update xs j a = xs := by funext i by_cases hi : i = j <;> simp [Function.update, hi, h]
theorem completed_joint_pushforward [Fintype I] [Fintype A] [Fintype B] [Fintype S] [DecidableEq A] [DecidableEq B] [DecidableEq S] (left : (A × S) → FiniteDistribution (I → A)) (right : (B × S) → FiniteDistribution (I → B)) (j : I) (hleft : ∀ q xs, (left q).weight xs ≠ 0 → xs j = q.1) (hright : ∀ q ys, (right q).weight ys ≠ 0 → ys j = q.1) (x : A × S) (y : B × S) : (seedLaw left right).pushforward (fun seed => (completedLeft j seed x, completedRight j seed y)) = (left x).product (right y) := by apply repaired_joint_pushforward left right (fun q xs => Function.update xs j q.1) (fun q ys => Function.update ys j q.1) · intro q xs h exact update_eq_of_coordinate xs j q.1 (hleft q xs h) · intro q ys h exact update_eq_of_coordinate ys j q.1 (hright q ys h)
end KernelSamplingendend MinUncutGames.Foundations.Games
namespace MinUncutGames.Foundations.Games.FiniteDistribution
open scoped BigOperatorsnoncomputable section
variable {Seed Ω : Type*} [Fintype Seed] [Fintype Ω]
def mixture (seedLaw : FiniteDistribution Seed) (laws : Seed → FiniteDistribution Ω) : FiniteDistribution Ω where weight x := ∑ seed, seedLaw.weight seed * (laws seed).weight x nonnegative x := Finset.sum_nonneg fun seed _ => mul_nonneg (seedLaw.nonnegative seed) ((laws seed).nonnegative x) normalized := by rw [Finset.sum_comm] simp_rw [← Finset.mul_sum, (laws _).normalized, mul_one] exact seedLaw.normalized
theorem probability_mixture (seedLaw : FiniteDistribution Seed) (laws : Seed → FiniteDistribution Ω) (event : Ω → Bool) : (seedLaw.mixture laws).probability event = ∑ seed, seedLaw.weight seed * (laws seed).probability event := by unfold probability mixture calc _ = ∑ x, ∑ seed, seedLaw.weight seed * (if event x then (laws seed).weight x else 0) := by apply Finset.sum_congr rfl intro x _ cases event x <;> simp _ = _ := by rw [Finset.sum_comm] apply Finset.sum_congr rfl intro seed _ rw [Finset.mul_sum]
theorem probability_mixture_le (seedLaw : FiniteDistribution Seed) (laws : Seed → FiniteDistribution Ω) (event : Ω → Bool) (bound : ℝ) (h : ∀ seed, (laws seed).probability event ≤ bound) : (seedLaw.mixture laws).probability event ≤ bound := by rw [probability_mixture] calc _ ≤ ∑ seed, seedLaw.weight seed * bound := Finset.sum_le_sum fun seed _ => mul_le_mul_of_nonneg_left (h seed) (seedLaw.nonnegative seed) _ = bound := by rw [← Finset.sum_mul, seedLaw.normalized, one_mul]
endend MinUncutGames.Foundations.Games.FiniteDistribution
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267import Mathlibimport OAI.Computability.MinUncut.Games.Basic
namespace OAI
namespace MinUncutGames.Foundations.CorrelatedSampling
noncomputable section
variable {σ α : Type*} [Fintype σ] [DecidableEq σ] [DecidableEq α]
def localSample (accept : σ → Bool) (decode : σ → α) (fallback : α) (proposals : List σ) : α := ((firstAccepted accept proposals).map decode).getD fallback
def localDiagonal (left right : σ → Bool) (decode : σ → α) (fallback a : α) (proposals : List σ) : ℝ := if localSample left decode fallback proposals = a ∧ localSample right decode fallback proposals = a then 1 else 0
def goodLabel (left right : σ → Bool) (decode : σ → α) (a : α) (s : σ) : Bool := (left s && right s) && decide (decode s = a)
omit [Fintype σ] [DecidableEq σ] intheorem common_first_label_lower (left right : σ → Bool) (decode : σ → α) (fallback a : α) (proposals : List σ) : goodFirstIndicator (fun s => left s || right s) (goodLabel left right decode a) proposals ≤ localDiagonal left right decode fallback a proposals := by cases hfirst : firstAccepted (fun s => left s || right s) proposals with | none => simp only [goodFirstIndicator, hfirst] unfold localDiagonal split_ifs <;> norm_num | some s => by_cases hc : goodLabel left right decode a s = true · have hparts : (left s = true ∧ right s = true) ∧ decode s = a := by simpa [goodLabel] using hc have h := first_union_common left right proposals s hfirst hparts.1.1 hparts.1.2 simp [goodFirstIndicator, hfirst, hc, localDiagonal, localSample, h.1, h.2, hparts.2] · have hn : 0 ≤ localDiagonal left right decode fallback a proposals := by unfold localDiagonal split_ifs <;> norm_num simpa [goodFirstIndicator, hfirst, hc] using hn
omit [DecidableEq σ] in theorem union_goodLabel_mass (w : σ → ℝ) (left right : σ → Bool) (decode : σ → α) (a : α) : eventMass w (fun s => (left s || right s) && goodLabel left right decode a s) = eventMass w (goodLabel left right decode a) := by unfold eventMass apply Finset.sum_congr rfl intro s _ cases hl : left s <;> cases hr : right s <;> simp [goodLabel, hl, hr]
theorem finite_label_diagonal_bound (w : σ → ℝ) (left right : σ → Bool) (decode : σ → α) (fallback a : α) (hw : ∀ s, 0 ≤ w s) (hw_sum : ∑ s, w s = 1) (hu : 0 < eventMass w (fun s => left s || right s)) (n : Nat) : eventMass w (goodLabel left right decode a) / eventMass w (fun s => left s || right s) * (1 - eventMass w (fun s => !(left s || right s)) ^ n) ≤ traceAverage w n (localDiagonal left right decode fallback a) := by have h := traceAverage_mono w hw n _ _ (common_first_label_lower left right decode fallback a) rw [goodFirstIndicator_law w _ _ hw_sum n, goodFirstMass_exact w _ _ hw_sum (ne_of_gt hu) n, union_goodLabel_mass] at h exact h
variable [Fintype α] [Nonempty α]
theorem rectangle_label_diagonal_bound (thresholds : List ℝ) (p q : α → ℝ) (fallback a : α) (hpm : ∀ x, p x ∈ thresholds) (hqm : ∀ x, q x ∈ thresholds) (hp0 : ∀ x, 0 ≤ p x) (hq0 : ∀ x, 0 ≤ q x) (hp1 : ∀ x, p x ≤ 1) (hq1 : ∀ x, q x ≤ 1) (hpsum : ∑ x, p x = 1) (hqsum : ∑ x, q x = 1) (n : Nat) : min (p a) (q a) / (1 + totalVariation p q) * (1 - eventMass (rectangleWeight thresholds) (fun s => !(rectangleAccept thresholds p s || rectangleAccept thresholds q s)) ^ n) ≤ traceAverage (rectangleWeight thresholds) n (localDiagonal (rectangleAccept thresholds p) (rectangleAccept thresholds q) Prod.fst fallback a) := by have hc : 0 < (Fintype.card α : ℝ) := by exact_mod_cast Fintype.card_pos have hU : 0 < unionMass p q := by rw [unionMass_eq p q hpsum hqsum] linarith [totalVariation_nonneg p q] have hmass := rectangle_union_mass thresholds p q hpm hqm hp0 hq0 hp1 hq1 have hu : 0 < eventMass (rectangleWeight thresholds) (fun s => rectangleAccept thresholds p s || rectangleAccept thresholds q s) := by rw [hmass] exact div_pos hU hc have h := finite_label_diagonal_bound (rectangleWeight thresholds) (rectangleAccept thresholds p) (rectangleAccept thresholds q) Prod.fst fallback a (rectangleWeight_nonnegative thresholds) (rectangleWeight_normalized thresholds) hu n unfold goodLabel at h rw [rectangle_common_label_mass thresholds p q a hpm hqm hp0 hq0 hp1 hq1, hmass] at h have hratio : (min (p a) (q a) / (Fintype.card α : ℝ)) / (unionMass p q / (Fintype.card α : ℝ)) = min (p a) (q a) / unionMass p q := by field_simp rw [hratio, unionMass_eq p q hpsum hqsum] at h exact h
end
open scoped BigOperators
noncomputable section
def profileThresholds {κ S : Type*} [Fintype κ] [Fintype S] (P : κ → S → ℝ) : List ℝ := by classical exact (Finset.univ.toList : List (κ × S)).map (fun ks => P ks.1 ks.2)
theorem mem_profileThresholds {κ S : Type*} [Fintype κ] [Fintype S] (P : κ → S → ℝ) (k : κ) (s : S) : P k s ∈ profileThresholds P := by classical exact List.mem_map.mpr ⟨(k, s), by simp, rfl⟩
theorem distribution_weight_le_one {S : Type*} [Fintype S] (μ : Games.FiniteDistribution S) (s : S) : μ.weight s ≤ 1 := by calc μ.weight s ≤ ∑ t, μ.weight t := Finset.single_le_sum (fun t _ => μ.nonnegative t) (Finset.mem_univ s) _ = 1 := μ.normalized
variable {Q₁ Q₂ S : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype S]
def sharedProfileThresholds (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) : List ℝ := profileThresholds (fun (k : Q₁ ⊕ Q₂) s => (Sum.elim L R k).weight s)
theorem left_mem_sharedProfileThresholds (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) (s : S) : (L x).weight s ∈ sharedProfileThresholds L R := by exact mem_profileThresholds _ (Sum.inl x) s
theorem right_mem_sharedProfileThresholds (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) (y : Q₂) (s : S) : (R y).weight s ∈ sharedProfileThresholds L R := by exact mem_profileThresholds _ (Sum.inr y) s
abbrev SharedProfileSeed (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) := RectangleSeed (sharedProfileThresholds L R) S
def sharedProfileLeft (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) : SharedProfileSeed L R → Bool := rectangleAccept (sharedProfileThresholds L R) (L x).weight
def sharedProfileRight (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) (y : Q₂) : SharedProfileSeed L R → Bool := rectangleAccept (sharedProfileThresholds L R) (R y).weight
def sharedProfileReject (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) (y : Q₂) : ℝ := eventMass (rectangleWeight (sharedProfileThresholds L R)) (fun s => !(sharedProfileLeft L R x s || sharedProfileRight L R y s))
def uniformRejectionRate (S : Type*) [Fintype S] : ℝ := 1 - 1 / (Fintype.card S : ℝ)
theorem uniformRejectionRate_nonnegative (S : Type*) [Fintype S] [Nonempty S] : 0 ≤ uniformRejectionRate S := by have hc : (0 : ℝ) < Fintype.card S := by exact_mod_cast (Fintype.card_pos : 0 < Fintype.card S) have hc₁ : (1 : ℝ) ≤ Fintype.card S := by exact_mod_cast (Nat.succ_le_of_lt (Fintype.card_pos : 0 < Fintype.card S)) apply sub_nonneg.mpr exact (div_le_iff₀ hc).2 (by simpa using hc₁)
theorem uniformRejectionRate_lt_one (S : Type*) [Fintype S] [Nonempty S] : uniformRejectionRate S < 1 := by have hc : (0 : ℝ) < Fintype.card S := by exact_mod_cast (Fintype.card_pos : 0 < Fintype.card S) have hp : (0 : ℝ) < 1 / (Fintype.card S : ℝ) := div_pos (by norm_num) hc dsimp [uniformRejectionRate] linarith
theorem sharedProfileReject_nonnegative [Nonempty S] (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) (y : Q₂) : 0 ≤ sharedProfileReject L R x y := by exact eventMass_nonneg _ _ (rectangleDistribution (α := S) (sharedProfileThresholds L R)).nonnegative
theorem sharedProfile_reject_le_rate [Nonempty S] (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) (y : Q₂) : sharedProfileReject L R x y ≤ uniformRejectionRate S := by let thresholds := sharedProfileThresholds L R have hsum : (∑ s : RectangleSeed thresholds S, rectangleWeight thresholds s) = 1 := (rectangleDistribution (α := S) thresholds).normalized have hcomp := eventMass_complement (rectangleWeight thresholds) (fun s => sharedProfileLeft L R x s || sharedProfileRight L R y s) hsum have hu : eventMass (rectangleWeight thresholds) (fun s => sharedProfileLeft L R x s || sharedProfileRight L R y s) = (1 + totalVariation (L x).weight (R y).weight) / (Fintype.card S : ℝ) := by change eventMass (rectangleWeight thresholds) (fun s => rectangleAccept thresholds (L x).weight s || rectangleAccept thresholds (R y).weight s) = _ rw [rectangle_union_mass thresholds (L x).weight (R y).weight (left_mem_sharedProfileThresholds L R x) (right_mem_sharedProfileThresholds L R y) (L x).nonnegative (R y).nonnegative (distribution_weight_le_one (L x)) (distribution_weight_le_one (R y))] rw [unionMass_eq (L x).weight (R y).weight (L x).normalized (R y).normalized] have hc : (0 : ℝ) < Fintype.card S := by exact_mod_cast (Fintype.card_pos : 0 < Fintype.card S) have htv := totalVariation_nonneg (L x).weight (R y).weight have hquot : 1 / (Fintype.card S : ℝ) ≤ (1 + totalVariation (L x).weight (R y).weight) / (Fintype.card S : ℝ) := (div_le_div_iff_of_pos_right hc).2 (by linarith) rw [hu] at hcomp change eventMass (rectangleWeight thresholds) (fun s => !(sharedProfileLeft L R x s || sharedProfileRight L R y s)) ≤ 1 - 1 / (Fintype.card S : ℝ) linarith
private theorem nonnegative_powers_mono (a b : ℝ) (ha : 0 ≤ a) (hab : a ≤ b) (n : ℕ) : a ^ n ≤ b ^ n := by have hb : 0 ≤ b := le_trans ha hab induction n with | zero => simp | succ n ih => rw [pow_succ, pow_succ] exact mul_le_mul ih hab ha (pow_nonneg hb n)
theorem sharedProfile_label_diagonal_bound [Nonempty S] [DecidableEq S] (L : Q₁ → Games.FiniteDistribution S) (R : Q₂ → Games.FiniteDistribution S) (x : Q₁) (y : Q₂) (fallback a : S) (n : ℕ) : min ((L x).weight a) ((R y).weight a) / (1 + totalVariation (L x).weight (R y).weight) * (1 - uniformRejectionRate S ^ n) ≤ traceAverage (rectangleWeight (sharedProfileThresholds L R)) n (localDiagonal (sharedProfileLeft L R x) (sharedProfileRight L R y) Prod.fst fallback a) := by have hp := nonnegative_powers_mono (sharedProfileReject L R x y) (uniformRejectionRate S) (sharedProfileReject_nonnegative L R x y) (sharedProfile_reject_le_rate L R x y) n have htv := totalVariation_nonneg (L x).weight (R y).weight have hm : 0 ≤ min ((L x).weight a) ((R y).weight a) / (1 + totalVariation (L x).weight (R y).weight) := div_nonneg (le_min ((L x).nonnegative a) ((R y).nonnegative a)) (by linarith) have hsurv : min ((L x).weight a) ((R y).weight a) / (1 + totalVariation (L x).weight (R y).weight) * (1 - uniformRejectionRate S ^ n) ≤ min ((L x).weight a) ((R y).weight a) / (1 + totalVariation (L x).weight (R y).weight) * (1 - sharedProfileReject L R x y ^ n) := mul_le_mul_of_nonneg_left (by linarith) hm refine hsurv.trans ?_ simpa only [sharedProfileReject, sharedProfileLeft, sharedProfileRight] using rectangle_label_diagonal_bound (sharedProfileThresholds L R) (L x).weight (R y).weight fallback a (left_mem_sharedProfileThresholds L R x) (right_mem_sharedProfileThresholds L R y) (L x).nonnegative (R y).nonnegative (distribution_weight_le_one (L x)) (distribution_weight_le_one (R y)) (L x).normalized (R y).normalized n
theorem exists_uniformRejectionRate_pow_lt (S : Type*) [Fintype S] [Nonempty S] (η : ℝ) (hη : 0 < η) : ∃ n : ℕ, uniformRejectionRate S ^ n < η := by have ht := tendsto_pow_atTop_nhds_zero_of_lt_one (uniformRejectionRate_nonnegative S) (uniformRejectionRate_lt_one S) exact (ht.eventually (gt_mem_nhds hη)).exists
end
end MinUncutGames.Foundations.CorrelatedSampling
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143import Mathlibimport OAI.Computability.MinUncut.Estimates.Densityimport OAI.Computability.MinUncut.Estimates.Convolution
namespace OAI
noncomputable sectionopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Filteropen scoped Topology NNRealopen scoped BigOperatorsopen MeasureTheory ProbabilityTheory Polynomial Filteropen scoped BigOperators Topologyopen MeasureTheory ProbabilityTheory WithLpopen scoped BigOperators RealInnerProductSpacenamespace MinUncut.RowNoiseopen BinaryFourieropen scoped BigOperatorslocal instance maskRowKernelDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] : Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintypevariable {R W : Type*} [Fintype R] [DecidableEq R] [Fintype W] [DecidableEq W] [AddCommGroup W] [Module F₂ W]
def maskRowKernel (active : Bool) (b c : W) : ℝ := if active then rowDensity 0 b c-1 else 1
omit [AddCommGroup W] [Module F₂ W] inlemma maskRowKernel_symmetric (active : Bool) (b c : W) : maskRowKernel active b c = maskRowKernel active c b := by simp only [maskRowKernel, rowDensity_symmetric]
omit [Module F₂ W] inlemma maskRowKernel_abs_mean (active : Bool) (b : W) : (𝔼 c, |maskRowKernel active b c|) ≤ if active then 2 else 1 := by cases active · simp [maskRowKernel] · dsimp only [maskRowKernel] calc _ ≤ 𝔼 c, (rowDensity 0 b c+1) := by apply Finset.expect_le_expect intro c _ exact (abs_sub _ _).trans (by rw [abs_of_nonneg (rowDensity_nonneg (by norm_num) (by norm_num) _ _), abs_one]) _ = 2 := by rw [Finset.expect_add_distrib, rowDensity_mean]; norm_num
lemma maskRowKernel_character (active : Bool) (b : W) (α : Module.Dual F₂ W) : (𝔼 c, maskRowKernel active b c * character α c) = if active = decide (α ≠ 0) then character α b else 0 := by cases active · simp [maskRowKernel, character_mean] split_ifs with h · simp [h] · rfl · simp only [maskRowKernel, ↓reduceIte, sub_mul, one_mul, Finset.expect_sub_distrib, row_character_eigen, character_mean] by_cases h : α=0 <;> simp [h]
def maskKernel (S : Finset R) (B C : R → W) : ℝ := ∏ r, maskRowKernel (decide (r ∈ S)) (B r) (C r)
omit [AddCommGroup W] [Module F₂ W] inlemma maskKernel_symmetric (S : Finset R) (B C : R → W) : maskKernel S B C = maskKernel S C B := by simp only [maskKernel, maskRowKernel_symmetric]
omit [Module F₂ W] inlemma maskKernel_abs_mean (S : Finset R) (B : R → W) : (𝔼 C, |maskKernel S B C|) ≤ (2 : ℝ)^Fintype.card R := by simp only [maskKernel, Finset.abs_prod] rw [expect_prod (f := fun r (c : W) => |maskRowKernel (decide (r ∈ S)) (B r) c|)] calc _ ≤ ∏ r : R, (2:ℝ) := by apply Finset.prod_le_prod₀ · intro r _; exact Finset.expect_nonneg (fun _ _ => abs_nonneg _) · intro r _ exact (maskRowKernel_abs_mean _ _).trans (by split_ifs <;> norm_num) _ = _ := by simp
lemma maskKernel_character (S : Finset R) (B : R → W) (α : Module.Dual F₂ (R → W)) : (𝔼 C, maskKernel S B C * character α C) = if mask α=S then character α B else 0 := by simp only [maskKernel, character_product, ← Finset.prod_mul_distrib] rw [expect_prod (f := fun r (c : W) => maskRowKernel (decide (r ∈ S)) (B r) c * character (frequency α r) c)] simp only [maskRowKernel_character] have he (r : R) : (decide (r ∈ S) = decide (frequency α r ≠ 0)) ↔ (r ∈ S ↔ r ∈ mask α) := by by_cases h₁ : r ∈ S <;> by_cases h₂ : frequency α r=0 <;> simp [mask, h₁, h₂] by_cases hs : mask α=S · rw [ite_eq_left hs] apply Finset.prod_congr rfl intro r _ rw [ite_eq_left ((he r).mpr (by rw [hs]))] · rw [ite_eq_right hs] have hh : ∃ r, ¬(r ∈ S ↔ r ∈ mask α) := by by_contra hn push Not at hn exact hs (Finset.ext (fun r => (hn r).symm)) obtain ⟨r,hr⟩ := hh exact Finset.prod_eq_zero (Finset.mem_univ r) (ite_eq_right (fun h => hr ((he r).mp h)))
def maskProject (S : Finset R) (f : (R → W) → ℝ) (B : R → W) : ℝ := 𝔼 C, maskKernel S B C * f C
lemma maskProject_expansion (S : Finset R) (f : (R → W) → ℝ) (B : R → W) : maskProject S f B = ∑ α : Module.Dual F₂ (R → W), if mask α=S then coefficient f α * character α B else 0 := by unfold maskProject conv_lhs => arg 2; ext C; rw [← inversion f C] simp only [Finset.mul_sum] rw [Finset.expect_sum_comm] apply Finset.sum_congr rfl intro α _ simp_rw [mul_left_comm _ (coefficient f α), ← Finset.mul_expect, maskKernel_character] split_ifs <;> simp
lemma coefficient_maskProject (S : Finset R) (f : (R → W) → ℝ) (α : Module.Dual F₂ (R → W)) : coefficient (maskProject S f) α = if mask α=S then coefficient f α else 0 := by have he (B : R → W) : maskProject S f B = ∑ β ∈ Finset.univ.filter (fun β : Module.Dual F₂ (R → W) => mask β=S), coefficient f β*character β B := by rw [maskProject_expansion, Finset.sum_filter] unfold coefficient simp_rw [he, Finset.sum_mul, Finset.expect_sum_comm, mul_assoc, ← Finset.mul_expect, character_orthogonality] simp [Finset.mem_filter, coefficient]
omit [Module F₂ W] inlemma maskProject_l1 (S : Finset R) (f : (R → W) → ℝ) : (𝔼 B, |maskProject S f B|) ≤ (2:ℝ)^Fintype.card R * (𝔼 B, |f B|) := by calc _ ≤ 𝔼 B, 𝔼 C, |maskKernel S B C| * |f C| := by apply Finset.expect_le_expect intro B _ simpa only [maskProject, abs_mul] using Finset.abs_expect_le Finset.univ (fun C => maskKernel S B C*f C) _ = 𝔼 C, (𝔼 B, |maskKernel S C B|)*|f C| := by rw [Finset.expect_comm] simp only [maskKernel_symmetric, Finset.expect_mul] _ ≤ 𝔼 C, (2:ℝ)^Fintype.card R * |f C| := by apply Finset.expect_le_expect intro C _ exact mul_le_mul_of_nonneg_right (maskKernel_abs_mean S C) (abs_nonneg _) _ = _ := (Finset.mul_expect _ _ _).symmend MinUncut.RowNoise
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757import Mathlibimport OAI.Computability.MinUncut.Estimates.FaceUpdateSelfimport OAI.Computability.MinUncut.Games.AffineLabelsimport OAI.Computability.MinUncut.Machines.OuterAlphabets
namespace OAI
noncomputable sectionopen scoped BigOperatorsnamespace MinUncut.Outeropen MinUncut.Innerattribute [local instance] Classical.propDecidablevariable {Name I : Type*}
abbrev SecondQuestion (Name : Type*) := Name ⊕ Equation Name
def secondSlotCount : SecondQuestion Name → ℕ | .inl _ => 1 | .inr _ => 3abbrev secondSlot (v : SecondQuestion Name) := Fin (secondSlotCount v) → F₂
abbrev FirstAlphabet (U : I → Equation Name) := ∀ j, alphabet (U j)abbrev FirstDirection (U : I → Equation Name) := ∀ j, (alphabet (U j)).directionabbrev SecondAlphabet (V : I → SecondQuestion Name) := ∀ j, secondSlot (V j)
def slotQuestion (E : Equation Name) (hidden : Bool) (p : Fin 3) : SecondQuestion Name := if hidden then .inl (E.names p) else .inr E
def slotProjection (E : Equation Name) (hidden : Bool) (p : Fin 3) : alphabet E →ᵃ[F₂] secondSlot (slotQuestion E hidden p) := by cases hidden · exact (alphabet E).subtype · exact (LinearMap.pi (fun _ : Fin 1 => (LinearMap.proj p : Triple →ₗ[F₂] F₂))).toAffineMap.comp (alphabet E).subtype
def secondQuestion (U : I → Equation Name) (hidden : I → Bool) (position : I → Fin 3) : I → SecondQuestion Name := fun j => slotQuestion (U j) (hidden j) (position j)
def projection (U : I → Equation Name) (hidden : I → Bool) (position : I → Fin 3) : FirstAlphabet U →ᵃ[F₂] SecondAlphabet (secondQuestion U hidden position) := AffineMap.pi (fun j => (slotProjection (U j) (hidden j) (position j)).comp (AffineMap.proj j))
@[simp] lemma projection_apply (U : I → Equation Name) (hidden : I → Bool) (position : I → Fin 3) (a : FirstAlphabet U) (j : I) : projection U hidden position a j=slotProjection (U j) (hidden j) (position j) (a j) := rfl
def evaluatedTriple (s : Name → F₂) (E : Equation Name) : Triple := fun p => s (E.names p)def Satisfied (s : Name → F₂) (E : Equation Name) : Prop := parity (evaluatedTriple s E)=E.rhs
lemma evaluatedTriple_valid (s : Name → F₂) (E : Equation Name) (h : Satisfied s E) : Valid E (evaluatedTriple s E) := ⟨h,fun _ _ he => congrArg s he⟩
def firstLabel (s : Name → F₂) (U : I → Equation Name) : FirstAlphabet U := fun j => if h : Satisfied s (U j) then ⟨evaluatedTriple s (U j),evaluatedTriple_valid s (U j) h⟩ else origin (U j)
def secondSlotLabel (s : Name → F₂) : (v : SecondQuestion Name) → secondSlot v | .inl x => fun _ => s x | .inr E => evaluatedTriple s E
def secondLabel (s : Name → F₂) (V : I → SecondQuestion Name) : SecondAlphabet V := fun j => secondSlotLabel s (V j)
lemma honest_slot (s : Name → F₂) (E : Equation Name) (h : Satisfied s E) (hidden : Bool) (p : Fin 3) : slotProjection E hidden p ⟨evaluatedTriple s E,evaluatedTriple_valid s E h⟩ = secondSlotLabel s (slotQuestion E hidden p) := by cases hidden <;> rfl
lemma honest_projection (s : Name → F₂) (U : I → Equation Name) (h : ∀ j, Satisfied s (U j)) (hidden : I → Bool) (position : I → Fin 3) : projection U hidden position (firstLabel s U) = secondLabel s (secondQuestion U hidden position) := by funext j change slotProjection (U j) (hidden j) (position j) (firstLabel s U j)=_ simp only [firstLabel,dite_eq_left (h j)] exact honest_slot s (U j) (h j) (hidden j) (position j)
open MinUncut.Innerattribute [local instance] Classical.propDecidablevariable {Name I : Type*} [Fintype I]
def slotFunctional (v : SecondQuestion Name) (β : F₂) (l : Module.Dual F₂ Triple) : Module.Dual F₂ (secondSlot v) := by cases v with | inl x => exact β • (LinearMap.proj (0 : Fin 1)) | inr E => exact l
lemma slotFunctional_add (v : SecondQuestion Name) (β γ : F₂) (l k : Module.Dual F₂ Triple) : slotFunctional v (β+γ) (l+k)=slotFunctional v β l + slotFunctional v γ k := by cases v with | inl x => exact add_smul _ _ _ | inr E => rfl
lemma slotFunctional_smul (v : SecondQuestion Name) (c β : F₂) (l : Module.Dual F₂ Triple) : slotFunctional v (c • β) (c • l)=c • slotFunctional v β l := by cases v with | inl x => change (c*β) • (LinearMap.proj (0 : Fin 1) : Module.Dual F₂ (Fin 1 → F₂)) = _ exact mul_smul _ _ _ | inr E => rfl
def directLinear (V : I → SecondQuestion Name) (β : I → F₂) (l : I → Module.Dual F₂ Triple) : Module.Dual F₂ (SecondAlphabet V) := ∑ j, (slotFunctional (V j) (β j) (l j)).comp (LinearMap.proj j)
def directHint (V : I → SecondQuestion Name) (κ : F₂) (β : I → F₂) (l : I → Module.Dual F₂ Triple) : Forms (SecondAlphabet V) := (directLinear V β l).toAffineMap + AffineMap.const F₂ _ κ
@[simp] lemma directHint_apply (V : I → SecondQuestion Name) (κ : F₂) (β : I → F₂) (l : I → Module.Dual F₂ Triple) (a : SecondAlphabet V) : directHint V κ β l a = (∑ j, slotFunctional (V j) (β j) (l j) (a j))+κ := by simp [directHint,directLinear]
lemma slotFunctional_project (E : Equation Name) (hidden : Bool) (p : Fin 3) (β : F₂) (l : Module.Dual F₂ Triple) (a : alphabet E) : slotFunctional (slotQuestion E hidden p) β l (slotProjection E hidden p a) = if hidden then β*a.val p else l a.val := by cases hidden <;> rfl
lemma pulledHint_apply (U : I → Equation Name) (hidden : I → Bool) (pos : I → Fin 3) (κ : F₂) (β : I → F₂) (l : I → Module.Dual F₂ Triple) (a : FirstAlphabet U) : formPullback (projection U hidden pos) (directHint (secondQuestion U hidden pos) κ β l) a = (∑ j, if hidden j then β j*(a j).val (pos j) else l j (a j).val)+κ := by change directHint (secondQuestion U hidden pos) κ β l (projection U hidden pos a)=_ rw [directHint_apply] congr 1 apply Finset.sum_congr rfl intro j _ exact slotFunctional_project (U j) (hidden j) (pos j) (β j) (l j) (a j)
lemma pulledHint_independent_active (U : I → Equation Name) (hidden : I → Bool) (pos pos' : I → Fin 3) (κ : F₂) (β : I → F₂) (l : I → Module.Dual F₂ Triple) (h : ∀ j, hidden j=true → pos j≠pos' j → β j=0) : formPullback (projection U hidden pos) (directHint (secondQuestion U hidden pos) κ β l) = formPullback (projection U hidden pos') (directHint (secondQuestion U hidden pos') κ β l) := by ext a rw [pulledHint_apply,pulledHint_apply] congr 1 apply Finset.sum_congr rfl intro j _ by_cases hh : hidden j=true · simp only [hh,↓reduceIte] by_cases hp : pos j=pos' j · rw [hp] · rw [h j hh hp]; simp · simp [hh]
def hintGenerator (V : I → SecondQuestion Name) : (F₂ × ((I → F₂) × (I → Module.Dual F₂ Triple))) →ₗ[F₂] Forms (SecondAlphabet V) where toFun c := directHint V c.1 c.2.1 c.2.2 map_add' c d := by ext a change directHint V (c.1+d.1) (c.2.1+d.2.1) (c.2.2+d.2.2) a = directHint V c.1 c.2.1 c.2.2 a + directHint V d.1 d.2.1 d.2.2 a simp only [directHint_apply,Pi.add_apply,slotFunctional_add,LinearMap.add_apply, Finset.sum_add_distrib] abel map_smul' k c := by ext a change directHint V (k • c.1) (k • c.2.1) (k • c.2.2) a = k • (directHint V c.1 c.2.1 c.2.2 a) simp only [directHint_apply,Pi.smul_apply,slotFunctional_smul,LinearMap.smul_apply, ← Finset.smul_sum,← smul_add]
def unpackFunctional : (v : SecondQuestion Name) → Module.Dual F₂ (secondSlot v) → F₂ × Module.Dual F₂ Triple | .inl _, l => (l (fun _ => 1),0) | .inr _, l => (0,l)
lemma oneSlotDual (l : Module.Dual F₂ (Fin 1 → F₂)) : l (fun _ => 1) • (LinearMap.proj (0 : Fin 1)) = l := by apply LinearMap.ext intro a have ha : a=a 0 • (fun _ : Fin 1 => (1 : F₂)) := by funext p fin_cases p simp change l (fun _ => 1)*a 0=l a calc _ = a 0 • l (fun _ => 1) := mul_comm _ _ _ = l (a 0 • (fun _ => 1)) := (l.map_smul _ _).symm _ = l a := congrArg l ha.symm
lemma slotFunctional_unpack (v : SecondQuestion Name) (l : Module.Dual F₂ (secondSlot v)) : slotFunctional v (unpackFunctional v l).1 (unpackFunctional v l).2=l := by cases v with | inl x => exact oneSlotDual l | inr E => rfl
lemma hintGenerator_surjective (V : I → SecondQuestion Name) : Function.Surjective (hintGenerator V) := by classical intro f let localPart (j : I) : Module.Dual F₂ (secondSlot (V j)) := f.linear.comp (LinearMap.single F₂ (fun j => secondSlot (V j)) j) let c := fun j => unpackFunctional (V j) (localPart j) refine ⟨(f 0,(fun j => (c j).1,fun j => (c j).2)),?_⟩ ext a change directHint V (f 0) (fun j => (c j).1) (fun j => (c j).2) a=f a rw [directHint_apply] have hlin : (∑ j,slotFunctional (V j) (c j).1 (c j).2 (a j))=f.linear a := by simp only [c,slotFunctional_unpack,localPart,LinearMap.comp_apply,LinearMap.single_apply] rw [← map_sum,Finset.univ_sum_single] rw [hlin] simpa using (f.map_vadd (0 : SecondAlphabet V) a).symm
attribute [local instance] BinaryFourier.dualFintype
lemma uniform_hintGenerator (V : I → SecondQuestion Name) (f : Forms (SecondAlphabet V) → ℝ) : (𝔼 c, f (hintGenerator V c)) = 𝔼 L, f L := IndependentSquares.expect_surjective_linear (hintGenerator V) (hintGenerator_surjective V) f
def hintTupleGenerator (V : I → SecondQuestion Name) (q : ℕ) : (Fin q → (F₂ × ((I → F₂) × (I → Module.Dual F₂ Triple)))) →ₗ[F₂] (Fin q → Forms (SecondAlphabet V)) := LinearMap.pi (fun k => (hintGenerator V).comp (LinearMap.proj k))
lemma hintTupleGenerator_surjective (V : I → SecondQuestion Name) (q : ℕ) : Function.Surjective (hintTupleGenerator V q) := by intro f choose c hc using fun k => hintGenerator_surjective V (f k) exact ⟨c,funext hc⟩
lemma uniform_hintTupleGenerator (V : I → SecondQuestion Name) (q : ℕ) (f : (Fin q → Forms (SecondAlphabet V)) → ℝ) : (𝔼 c, f (hintTupleGenerator V q c)) = 𝔼 L, f L := IndependentSquares.expect_surjective_linear (hintTupleGenerator V q) (hintTupleGenerator_surjective V q) f
end MinUncut.Outer
endnamespace MinUncutGames.Foundations.Games
open scoped BigOperators
noncomputable section
structure FiniteDistribution (Ω : Type*) [Fintype Ω] where weight : Ω → ℝ nonnegative : ∀ x, 0 ≤ weight x normalized : ∑ x, weight x = 1
namespace FiniteDistribution
variable {Ω Γ : Type*} [Fintype Ω] [Fintype Γ]
def expectation (μ : FiniteDistribution Ω) (f : Ω → ℝ) : ℝ := ∑ x, μ.weight x * f x
def probability (μ : FiniteDistribution Ω) (event : Ω → Bool) : ℝ := ∑ x, if event x then μ.weight x else 0
theorem probability_nonnegative (μ : FiniteDistribution Ω) (event : Ω → Bool) : 0 ≤ μ.probability event := by apply Finset.sum_nonneg intro x _ split · exact μ.nonnegative x · exact le_rfl
theorem probability_le_one (μ : FiniteDistribution Ω) (event : Ω → Bool) : μ.probability event ≤ 1 := by rw [← μ.normalized] apply Finset.sum_le_sum intro x _ split · exact le_rfl · exact μ.nonnegative x
@[simp] theorem probability_true (μ : FiniteDistribution Ω) : μ.probability (fun _ => true) = 1 := by simpa [probability] using μ.normalized
@[simp] theorem probability_false (μ : FiniteDistribution Ω) : μ.probability (fun _ => false) = 0 := by simp [probability]
theorem probability_mono (μ : FiniteDistribution Ω) {event event' : Ω → Bool} (h : ∀ x, event x = true → event' x = true) : μ.probability event ≤ μ.probability event' := by apply Finset.sum_le_sum intro x _ by_cases hx : event x = true · simp [hx, h x hx] · simp [hx] split · exact μ.nonnegative x · exact le_rfl
def pushforward (μ : FiniteDistribution Ω) (f : Ω → Γ) : FiniteDistribution Γ := by classical exact { weight := fun y => ∑ x, if f x = y then μ.weight x else 0 nonnegative := fun y => Finset.sum_nonneg fun x _ => by split · exact μ.nonnegative x · exact le_rfl normalized := by rw [Finset.sum_comm] simpa using μ.normalized }
theorem probability_pushforward (μ : FiniteDistribution Ω) (f : Ω → Γ) (event : Γ → Bool) : (μ.pushforward f).probability event = μ.probability (fun x => event (f x)) := by classical simp only [probability, pushforward] calc _ = ∑ y, ∑ x, if f x = y then (if event y then μ.weight x else 0) else 0 := by apply Finset.sum_congr rfl intro y _ by_cases hy : event y = true <;> simp [hy] _ = _ := by rw [Finset.sum_comm]; simp
def transport (μ : FiniteDistribution Ω) (equiv : Ω ≃ Γ) : FiniteDistribution Γ where weight y := μ.weight (equiv.symm y) nonnegative y := μ.nonnegative (equiv.symm y) normalized := by rw [equiv.symm.sum_comp, μ.normalized]
theorem probability_transport (μ : FiniteDistribution Ω) (equiv : Ω ≃ Γ) (event : Γ → Bool) : (μ.transport equiv).probability event = μ.probability (fun x => event (equiv x)) := by unfold probability transport exact Fintype.sum_equiv equiv.symm _ _ (fun _ => by simp)
def iid (μ : FiniteDistribution Ω) (n : Nat) : FiniteDistribution (Fin n → Ω) where weight x := ∏ i, μ.weight (x i) nonnegative x := Finset.prod_nonneg fun i _ => μ.nonnegative (x i) normalized := by rw [← Fintype.sum_pow, μ.normalized, one_pow]
theorem probability_iid_all (μ : FiniteDistribution Ω) (event : Ω → Bool) (n : Nat) : (μ.iid n).probability (fun x => decide (∀ i, event (x i) = true)) = μ.probability event ^ n := by classical unfold probability iid rw [Fintype.sum_pow] apply Finset.sum_congr rfl intro x _ simp only [decide_eq_true_eq] by_cases h : ∀ i, event (x i) = true · simp [h] · rw [ite_eq_right h] obtain ⟨i, hi⟩ := not_forall.mp h symm apply Finset.prod_eq_zero (Finset.mem_univ i) simp [hi]
end FiniteDistribution
abbrev Strategy (Q₁ Q₂ A₁ A₂ : Type*) := (Q₁ → A₁) × (Q₂ → A₂)
structure Game (Q₁ Q₂ A₁ A₂ : Type*) [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] where questions : FiniteDistribution (Q₁ × Q₂) accepts : Q₁ → Q₂ → A₁ → A₂ → Bool
namespace Game
variable {Q₁ Q₂ A₁ A₂ : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂]
def wins (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) (questions : Q₁ × Q₂) : Bool := G.accepts questions.1 questions.2 (strategy.1 questions.1) (strategy.2 questions.2)
def success (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) : ℝ := G.questions.probability (G.wins strategy)
theorem success_nonnegative (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) : 0 ≤ G.success strategy := G.questions.probability_nonnegative _
theorem success_le_one (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) : G.success strategy ≤ 1 := G.questions.probability_le_one _
def simulatedStrategy {R₁ R₂ B₁ B₂ : Type*} (questionMap₁ : Q₁ → R₁) (questionMap₂ : Q₂ → R₂) (answerMap₁ : Q₁ → B₁ → A₁) (answerMap₂ : Q₂ → B₂ → A₂) (strategy : Strategy R₁ R₂ B₁ B₂) : Strategy Q₁ Q₂ A₁ A₂ := (fun x => answerMap₁ x (strategy.1 (questionMap₁ x)), fun y => answerMap₂ y (strategy.2 (questionMap₂ y)))
theorem success_le_of_localSimulation {R₁ R₂ B₁ B₂ : Type*} [Fintype R₁] [Fintype R₂] [Fintype B₁] [Fintype B₂] (G : Game Q₁ Q₂ A₁ A₂) (H : Game R₁ R₂ B₁ B₂) (questionMap₁ : Q₁ → R₁) (questionMap₂ : Q₂ → R₂) (answerMap₁ : Q₁ → B₁ → A₁) (answerMap₂ : Q₂ → B₂ → A₂) (questionLaw : H.questions = G.questions.pushforward (fun q => (questionMap₁ q.1, questionMap₂ q.2))) (acceptance : ∀ x y a b, H.accepts (questionMap₁ x) (questionMap₂ y) a b = true → G.accepts x y (answerMap₁ x a) (answerMap₂ y b) = true) (strategy : Strategy R₁ R₂ B₁ B₂) : H.success strategy ≤ G.success (simulatedStrategy questionMap₁ questionMap₂ answerMap₁ answerMap₂ strategy) := by unfold success rw [questionLaw, FiniteDistribution.probability_pushforward] apply FiniteDistribution.probability_mono intro questions h exact acceptance questions.1 questions.2 _ _ h
def tupleQuestionEquiv (n : Nat) : (Fin n → Q₁ × Q₂) ≃ (Fin n → Q₁) × (Fin n → Q₂) where toFun questions := (fun i => (questions i).1, fun i => (questions i).2) invFun questions := fun i => (questions.1 i, questions.2 i) left_inv _ := rfl right_inv _ := rfl
def repetition (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) : Game (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂) := by classical exact { questions := (G.questions.iid n).transport (tupleQuestionEquiv n) accepts := fun x y a b => decide (∀ i, G.accepts (x i) (y i) (a i) (b i) = true) }
def repeatStrategy (strategy : Strategy Q₁ Q₂ A₁ A₂) (n : Nat) : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂) := (fun x i => strategy.1 (x i), fun y i => strategy.2 (y i))
theorem success_repeatStrategy (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) (n : Nat) : (G.repetition n).success (repeatStrategy strategy n) = G.success strategy ^ n := by unfold success change ((G.questions.iid n).transport (tupleQuestionEquiv n)).probability _ = _ rw [FiniteDistribution.probability_transport] exact G.questions.probability_iid_all (G.wins strategy) n
@[simp] theorem repetition_question_weight (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) (questions : (Fin n → Q₁) × (Fin n → Q₂)) : (G.repetition n).questions.weight questions = ∏ i, G.questions.weight (questions.1 i, questions.2 i) := rfl
@[simp] theorem repetition_accepts_iff (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) (x : Fin n → Q₁) (y : Fin n → Q₂) (a : Fin n → A₁) (b : Fin n → A₂) : (G.repetition n).accepts x y a b = true ↔ ∀ i, G.accepts (x i) (y i) (a i) (b i) = true := by classical simp [repetition]
def coordinateWin (G : Game Q₁ Q₂ A₁ A₂) {n : Nat} (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) (coordinate : Fin n) (questions : (Fin n → Q₁) × (Fin n → Q₂)) : Bool := G.accepts (questions.1 coordinate) (questions.2 coordinate) (strategy.1 questions.1 coordinate) (strategy.2 questions.2 coordinate)
def selectedWins (G : Game Q₁ Q₂ A₁ A₂) {n : Nat} (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) (selected : Finset (Fin n)) (questions : (Fin n → Q₁) × (Fin n → Q₂)) : Bool := by classical exact decide (∀ i ∈ selected, G.coordinateWin strategy i questions = true)
theorem selectedWins_mono (G : Game Q₁ Q₂ A₁ A₂) {n : Nat} (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) {selected selected' : Finset (Fin n)} (h : selected ⊆ selected') : (G.repetition n).questions.probability (G.selectedWins strategy selected') ≤ (G.repetition n).questions.probability (G.selectedWins strategy selected) := by apply FiniteDistribution.probability_mono intro questions hwin simp only [selectedWins, decide_eq_true_eq] at hwin ⊢ intro i hi exact hwin i (h hi)
@[simp] theorem selectedWins_empty (G : Game Q₁ Q₂ A₁ A₂) {n : Nat} (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) (questions : (Fin n → Q₁) × (Fin n → Q₂)) : G.selectedWins strategy ∅ questions = true := by simp [selectedWins]
theorem selectedWins_univ (G : Game Q₁ Q₂ A₁ A₂) {n : Nat} (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) : G.selectedWins strategy Finset.univ = (G.repetition n).wins strategy := by classical funext questions simp [selectedWins, coordinateWin, repetition, wins]
variable {Q₁ Q₂ A₁ A₂ : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] [Nonempty A₁] [Nonempty A₂]
def value (G : Game Q₁ Q₂ A₁ A₂) : ℝ := by classical exact Finset.univ.sup' Finset.univ_nonempty G.success
theorem success_le_value (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) : G.success strategy ≤ G.value := by classical exact Finset.le_sup' G.success (Finset.mem_univ strategy)
theorem value_le_iff (G : Game Q₁ Q₂ A₁ A₂) (bound : ℝ) : G.value ≤ bound ↔ ∀ strategy : Strategy Q₁ Q₂ A₁ A₂, G.success strategy ≤ bound := by classical simp [value, Finset.sup'_le_iff]
theorem exists_optimal_strategy (G : Game Q₁ Q₂ A₁ A₂) : ∃ strategy : Strategy Q₁ Q₂ A₁ A₂, G.success strategy = G.value := by classical obtain ⟨strategy, _, h⟩ := Finset.exists_mem_eq_sup' (s := (Finset.univ : Finset (Strategy Q₁ Q₂ A₁ A₂))) Finset.univ_nonempty G.success exact ⟨strategy, h.symm⟩
theorem value_nonnegative (G : Game Q₁ Q₂ A₁ A₂) : 0 ≤ G.value := by obtain ⟨strategy, h⟩ := G.exists_optimal_strategy rw [← h] exact G.success_nonnegative strategy
theorem value_le_one (G : Game Q₁ Q₂ A₁ A₂) : G.value ≤ 1 := (G.value_le_iff 1).2 G.success_le_one
theorem randomized_success_le_value (G : Game Q₁ Q₂ A₁ A₂) {Seed : Type*} [Fintype Seed] (seedLaw : FiniteDistribution Seed) (strategies : Seed → Strategy Q₁ Q₂ A₁ A₂) : seedLaw.expectation (fun seed => G.success (strategies seed)) ≤ G.value := by unfold FiniteDistribution.expectation calc _ ≤ ∑ seed, seedLaw.weight seed * G.value := by apply Finset.sum_le_sum intro seed _ exact mul_le_mul_of_nonneg_left (G.success_le_value _) (seedLaw.nonnegative seed) _ = G.value := by rw [← Finset.sum_mul, seedLaw.normalized, one_mul]
omit [Nonempty A₁] [Nonempty A₂] intheorem success_repetition_zero (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy (Fin 0 → Q₁) (Fin 0 → Q₂) (Fin 0 → A₁) (Fin 0 → A₂)) : (G.repetition 0).success strategy = 1 := by have h : (G.repetition 0).wins strategy = fun _ => true := by funext questions simp [wins, repetition] unfold success rw [h, FiniteDistribution.probability_true]
@[simp] theorem value_repetition_zero (G : Game Q₁ Q₂ A₁ A₂) : (G.repetition 0).value = 1 := by obtain ⟨strategy, h⟩ := (G.repetition 0).exists_optimal_strategy rw [← h] exact G.success_repetition_zero strategy
theorem pow_value_le_repetition_value (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) : G.value ^ n ≤ (G.repetition n).value := by obtain ⟨strategy, h⟩ := G.exists_optimal_strategy rw [← h, ← G.success_repeatStrategy strategy n] exact (G.repetition n).success_le_value (repeatStrategy strategy n)
theorem value_le_of_localSimulation {R₁ R₂ B₁ B₂ : Type*} [Fintype R₁] [Fintype R₂] [Fintype B₁] [Fintype B₂] [Nonempty B₁] [Nonempty B₂] (G : Game Q₁ Q₂ A₁ A₂) (H : Game R₁ R₂ B₁ B₂) (questionMap₁ : Q₁ → R₁) (questionMap₂ : Q₂ → R₂) (answerMap₁ : Q₁ → B₁ → A₁) (answerMap₂ : Q₂ → B₂ → A₂) (questionLaw : H.questions = G.questions.pushforward (fun q => (questionMap₁ q.1, questionMap₂ q.2))) (acceptance : ∀ x y a b, H.accepts (questionMap₁ x) (questionMap₂ y) a b = true → G.accepts x y (answerMap₁ x a) (answerMap₂ y b) = true) : H.value ≤ G.value := by apply (H.value_le_iff _).2 intro strategy exact (G.success_le_of_localSimulation H questionMap₁ questionMap₂ answerMap₁ answerMap₂ questionLaw acceptance strategy).trans (G.success_le_value _)
end Game
namespace FiniteDistributionvariable {Ω Γ Q A : Type*} [Fintype Ω] [Fintype Γ] [Fintype Q] [Fintype A]
theorem eq_of_weight_eq {μ ν : FiniteDistribution Ω} (h : ∀ x, μ.weight x = ν.weight x) : μ = ν := by cases μ with | mk w hw hs => cases ν with | mk w' hw' hs' => have he : w = w' := funext h cases he rfl
def table [DecidableEq Q] (responses : Q → FiniteDistribution A) : FiniteDistribution (Q → A) := by classical exact { weight := fun answers => ∏ q, (responses q).weight (answers q) nonnegative := fun answers => Finset.prod_nonneg fun q _ => (responses q).nonnegative (answers q) normalized := by rw [← Fintype.prod_sum] simp only [FiniteDistribution.normalized, Finset.prod_const_one] }
theorem expectation_table_eval [DecidableEq Q] (responses : Q → FiniteDistribution A) (q₀ : Q) (h : A → ℝ) : (table responses).expectation (fun answers => h (answers q₀)) = (responses q₀).expectation h := by classical change (∑ answers : Q → A, (∏ q, (responses q).weight (answers q)) * h (answers q₀)) = ∑ a, (responses q₀).weight a * h a calc _ = ∑ answers : Q → A, ∏ q, (responses q).weight (answers q) * (if q = q₀ then h (answers q) else 1) := by apply Finset.sum_congr rfl intro answers _ rw [Finset.prod_mul_distrib] simp _ = ∏ q, ∑ a, (responses q).weight a * (if q = q₀ then h a else 1) := (Fintype.prod_sum (fun q a => (responses q).weight a * (if q = q₀ then h a else 1))).symm _ = ∏ q : Q, if q = q₀ then (∑ a, (responses q₀).weight a * h a) else 1 := by apply Finset.prod_congr rfl intro q _ by_cases hq : q = q₀ · subst q simp · simp [hq, (responses q).normalized] _ = _ := by simp
theorem table_eval_pushforward [DecidableEq Q] (responses : Q → FiniteDistribution A) (q₀ : Q) : (table responses).pushforward (fun answers => answers q₀) = responses q₀ := by classical apply eq_of_weight_eq intro a calc _ = (table responses).expectation (fun answers => if answers q₀ = a then 1 else 0) := by simp [pushforward, expectation, mul_ite] _ = (responses q₀).expectation (fun b => if b = a then 1 else 0) := expectation_table_eval responses q₀ (fun b => if b = a then (1 : ℝ) else 0) _ = _ := by simp [expectation, mul_ite]
def product (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ) : FiniteDistribution (Ω × Γ) where weight x := μ.weight x.1 * ν.weight x.2 nonnegative x := mul_nonneg (μ.nonnegative _) (ν.nonnegative _) normalized := by rw [Fintype.sum_prod_type] simp_rw [← Finset.mul_sum, ν.normalized, mul_one] exact μ.normalized
theorem expectation_product (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ) (f : Ω × Γ → ℝ) : (μ.product ν).expectation f = μ.expectation (fun x => ν.expectation (fun y => f (x,y))) := by simp only [expectation, product, Fintype.sum_prod_type, Finset.mul_sum, mul_assoc]
theorem expectation_comm (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ) (f : Ω → Γ → ℝ) : μ.expectation (fun x => ν.expectation (f x)) = ν.expectation (fun y => μ.expectation (fun x => f x y)) := by unfold expectation simp_rw [Finset.mul_sum] rw [Finset.sum_comm] apply Finset.sum_congr rfl intro y _ apply Finset.sum_congr rfl intro x _ exact mul_left_comm _ _ _
theorem expectation_congr (μ : FiniteDistribution Ω) {f g : Ω → ℝ} (h : ∀ x, f x = g x) : μ.expectation f = μ.expectation g := by unfold expectation apply Finset.sum_congr rfl intro x _ rw [h x]end FiniteDistribution
namespace Gamevariable {Q₁ Q₂ A₁ A₂ : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] [DecidableEq Q₁] [DecidableEq Q₂]
def responseTableLaw (responses₁ : Q₁ → FiniteDistribution A₁) (responses₂ : Q₂ → FiniteDistribution A₂) : FiniteDistribution (Strategy Q₁ Q₂ A₁ A₂) := by classical exact (FiniteDistribution.table responses₁).product (FiniteDistribution.table responses₂)
def stochasticSuccess (G : Game Q₁ Q₂ A₁ A₂) (responses₁ : Q₁ → FiniteDistribution A₁) (responses₂ : Q₂ → FiniteDistribution A₂) : ℝ := G.questions.expectation (fun q => (responses₁ q.1).expectation (fun a => (responses₂ q.2).expectation (fun b => if G.accepts q.1 q.2 a b then 1 else 0)))
omit [DecidableEq Q₁] [DecidableEq Q₂] intheorem success_eq_question_expectation (G : Game Q₁ Q₂ A₁ A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) : G.success strategy = G.questions.expectation (fun q => if G.wins strategy q then 1 else 0) := by simp [success, FiniteDistribution.probability, FiniteDistribution.expectation, mul_ite]
theorem table_success_eq_stochastic (G : Game Q₁ Q₂ A₁ A₂) (responses₁ : Q₁ → FiniteDistribution A₁) (responses₂ : Q₂ → FiniteDistribution A₂) : (responseTableLaw responses₁ responses₂).expectation G.success = G.stochasticSuccess responses₁ responses₂ := by classical unfold stochasticSuccess calc _ = (responseTableLaw responses₁ responses₂).expectation (fun strategy => G.questions.expectation (fun q => if G.wins strategy q then 1 else 0)) := FiniteDistribution.expectation_congr _ (G.success_eq_question_expectation) _ = G.questions.expectation (fun q => (responseTableLaw responses₁ responses₂).expectation (fun strategy => if G.wins strategy q then 1 else 0)) := FiniteDistribution.expectation_comm _ _ _ _ = _ := by apply FiniteDistribution.expectation_congr intro q rw [responseTableLaw, FiniteDistribution.expectation_product] change (FiniteDistribution.table responses₁).expectation (fun answers₁ => (FiniteDistribution.table responses₂).expectation (fun answers₂ => if G.accepts q.1 q.2 (answers₁ q.1) (answers₂ q.2) then 1 else 0)) = _ calc _ = (FiniteDistribution.table responses₁).expectation (fun answers₁ => (responses₂ q.2).expectation (fun b => if G.accepts q.1 q.2 (answers₁ q.1) b then 1 else 0)) := by apply FiniteDistribution.expectation_congr intro answers₁ exact FiniteDistribution.expectation_table_eval responses₂ q.2 (fun b => if G.accepts q.1 q.2 (answers₁ q.1) b then (1 : ℝ) else 0) _ = _ := FiniteDistribution.expectation_table_eval responses₁ q.1 (fun a => (responses₂ q.2).expectation (fun b => if G.accepts q.1 q.2 a b then (1 : ℝ) else 0))
variable [Nonempty A₁] [Nonempty A₂]
theorem stochasticSuccess_le_value (G : Game Q₁ Q₂ A₁ A₂) (responses₁ : Q₁ → FiniteDistribution A₁) (responses₂ : Q₂ → FiniteDistribution A₂) : G.stochasticSuccess responses₁ responses₂ ≤ G.value := by classical rw [← G.table_success_eq_stochastic] exact G.randomized_success_le_value (responseTableLaw responses₁ responses₂) id
theorem exists_deterministic_ge_stochastic (G : Game Q₁ Q₂ A₁ A₂) (responses₁ : Q₁ → FiniteDistribution A₁) (responses₂ : Q₂ → FiniteDistribution A₂) : ∃ strategy : Strategy Q₁ Q₂ A₁ A₂, G.stochasticSuccess responses₁ responses₂ ≤ G.success strategy := by obtain ⟨strategy, h⟩ := G.exists_optimal_strategy refine ⟨strategy, ?_⟩ rw [h] exact G.stochasticSuccess_le_value responses₁ responses₂end Gameendend MinUncutGames.Foundations.Games
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import Mathlibimport OAI.Computability.MinUncut.PCP.SelectionSequenceimport OAI.Computability.MinUncut.PCP.Game
namespace OAI
sectionnamespace MinUncutGames.Integration.SourceParameters
def rate (gap : ℚ) : ℚ := 1 - gap ^ 3 / 100000
theorem rate_bounds {gap : ℚ} (hgap : 0 < gap) (hgap1 : gap ≤ 1) : 0 < rate gap ∧ rate gap < 1 := by have hcube : gap ^ 3 ≤ 1 := pow_le_one₀ hgap.le hgap1 have hcubePos : 0 < gap ^ 3 := pow_pos hgap _ constructor <;> unfold rate <;> linarith
theorem fourth_power_comparison {gap : ℚ} (hgap : 0 ≤ gap) (hgap1 : gap ≤ 1) : 1 - (gap : ℝ) ^ 3 / 6000 ≤ (rate gap : ℝ) ^ 4 := by have hg : (0 : ℝ) ≤ gap := by exact_mod_cast hgap have hg1 : (gap : ℝ) ≤ 1 := by exact_mod_cast hgap1 have hc : (gap : ℝ) ^ 3 ≤ 1 := pow_le_one₀ hg hg1 have hc0 : 0 ≤ (gap : ℝ) ^ 3 := pow_nonneg hg _ have hb := one_add_mul_le_pow (a := -(gap : ℝ) ^ 3 / 100000) (by linarith : (-2 : ℝ) ≤ -(gap : ℝ) ^ 3 / 100000) 4 have hr : (rate gap : ℝ) = 1 - (gap : ℝ) ^ 3 / 100000 := by simp only [rate, Rat.cast_sub, Rat.cast_one, Rat.cast_div, Rat.cast_pow, Rat.cast_ofNat] rw [hr] calc _ ≤ 1 + 4 * (-(gap : ℝ) ^ 3 / 100000) := by linarith _ ≤ _ := by simpa only [Nat.cast_ofNat, sub_eq_add_neg, neg_div] using hb
theorem four_bit_rate_comparison {gap : ℚ} (hgap : 0 < gap) (hgap1 : gap ≤ 1) (n : Nat) : (1 - (gap : ℝ) ^ 3 / 6000) ^ ((n : ℝ) / 4) ≤ (rate gap : ℝ) ^ n := by have hg : (0 : ℝ) ≤ gap := by exact_mod_cast hgap.le have hg1 : (gap : ℝ) ≤ 1 := by exact_mod_cast hgap1 have hc : (gap : ℝ) ^ 3 ≤ 1 := pow_le_one₀ hg hg1 have hr : (0 : ℝ) ≤ rate gap := by exact_mod_cast (rate_bounds hgap hgap1).1.le calc _ ≤ ((rate gap : ℝ) ^ 4) ^ ((n : ℝ) / 4) := Real.rpow_le_rpow (by linarith) (fourth_power_comparison hgap.le hgap1) (by positivity) _ = (rate gap : ℝ) ^ ((4 : ℝ) * ((n : ℝ) / 4)) := (Real.rpow_natCast_mul hr 4 ((n : ℝ) / 4)).symm _ = (rate gap : ℝ) ^ (n : ℝ) := by congr 1; ring _ = _ := Real.rpow_natCast _ _
theorem logTwo_sixteen : MinUncutGames.Foundations.Repetition.logTwo 16 = 4 := by unfold MinUncutGames.Foundations.Repetition.logTwo rw [show (16 : ℝ) = 2 ^ 4 by norm_num, Real.log_pow] have hlog : Real.log 2 ≠ 0 := ne_of_gt (Real.log_pos (by norm_num : (1 : ℝ) < 2)) simp [hlog]
theorem game_repetition_rate {Q₁ Q₂ A₁ A₂ : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] [Nonempty A₁] [Nonempty A₂] [DecidableEq Q₁] [DecidableEq Q₂] (G : MinUncutGames.Foundations.Games.Game Q₁ Q₂ A₁ A₂) {gap : ℚ} (hgap : 0 < gap) (hgap1 : gap ≤ 1) (hcards : Fintype.card A₁ * Fintype.card A₂ = 16) (hvalue : G.value ≤ 1 - (gap : ℝ)) (n : Nat) : (G.repetition n).value ≤ (rate gap : ℝ) ^ n := by have hg : (0 : ℝ) < gap := by exact_mod_cast hgap have halphabet : MinUncutGames.Foundations.Repetition.logTwo ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ 4 := by rw [← Nat.cast_mul, hcards] exact logTwo_sixteen.le have h := MinUncutGames.Foundations.Repetition.holenstein_repetition_value G n hvalue (by linarith) (by norm_num : (1 : ℝ) ≤ 4) halphabet simp only [sub_sub_cancel] at h exact h.trans (four_bit_rate_comparison hgap hgap1 n)
def sourceThreshold (D : Nat) (δ : ℚ) : ℚ := 4 * (D : ℚ)⁻¹ * δ ^ 2
theorem sourceThreshold_pos {D : Nat} (hD : 0 < D) {δ : ℚ} (hδ : 0 < δ) : 0 < sourceThreshold D δ := by unfold sourceThreshold positivity
theorem exists_repetition_length {gap δ : ℚ} (hgap : 0 < gap) (hgap1 : gap ≤ 1) (hδ : 0 < δ) {D : Nat} (hD : 0 < D) : ∃ u : Nat, 0 < u ∧ (rate gap) ^ u < sourceThreshold D δ := MinUncutGames.Soundness.RepetitionUpper.exists_power_lt (rate gap) (sourceThreshold D δ) (rate_bounds hgap hgap1).1.le (rate_bounds hgap hgap1).2 (sourceThreshold_pos hD hδ)
def repetitionLength (gap δ : ℚ) (hgap : 0 < gap) (hgap1 : gap ≤ 1) (hδ : 0 < δ) (D : Nat) (hD : 0 < D) : Nat := Nat.find (exists_repetition_length hgap hgap1 hδ hD)
theorem repetitionLength_spec (gap δ : ℚ) (hgap : 0 < gap) (hgap1 : gap ≤ 1) (hδ : 0 < δ) (D : Nat) (hD : 0 < D) : 0 < repetitionLength gap δ hgap hgap1 hδ D hD ∧ rate gap ^ repetitionLength gap δ hgap hgap1 hδ D hD < sourceThreshold D δ := Nat.find_spec (exists_repetition_length hgap hgap1 hδ hD)
theorem repetitionLength_real_bound (gap δ : ℚ) (hgap : 0 < gap) (hgap1 : gap ≤ 1) (hδ : 0 < δ) (D : Nat) (hD : 0 < D) : (rate gap : ℝ) ^ repetitionLength gap δ hgap hgap1 hδ D hD ≤ 4 * (D : ℝ)⁻¹ * (δ : ℝ) ^ 2 := by have h := (repetitionLength_spec gap δ hgap hgap1 hδ D hD).2.le unfold sourceThreshold at h have hr := (Rat.cast_le (K := ℝ)).mpr h push_cast at hr exact hr
end MinUncutGames.Integration.SourceParameters
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517import Mathlibimport OAI.Computability.MinUncut.Games.Sampling
namespace OAI
namespace MinUncutGames.Foundations.Information
open scoped BigOperators
variable {α : Type*} [Fintype α]
noncomputable def hellingerSquared (p q : α → ℝ) : ℝ := ∑ a, (Real.sqrt (p a) - Real.sqrt (q a)) ^ 2
theorem sqrt_distance_le_relativeEntropy_term {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hs : x ≠ 0 → y ≠ 0) : (Real.sqrt x - Real.sqrt y)^2 ≤ x * Real.log (x / y) - x + y := by by_cases hxzero : x = 0 · subst x simp [Real.sq_sqrt hy] have hxpos : 0 < x := lt_of_le_of_ne hx (Ne.symm hxzero) have hypos : 0 < y := lt_of_le_of_ne hy (Ne.symm (hs hxzero)) have hsx : 0 < Real.sqrt x := Real.sqrt_pos.2 hxpos have hsy : 0 < Real.sqrt y := Real.sqrt_pos.2 hypos have hlog := Real.log_le_sub_one_of_pos (div_pos hsy hsx) have hlogid : Real.log (Real.sqrt y / Real.sqrt x) = -(Real.log (x / y)) / 2 := by rw [Real.log_div hsy.ne' hsx.ne', Real.log_sqrt hy, Real.log_sqrt hx, Real.log_div hxzero (hs hxzero)] ring have hprod : x * (Real.sqrt y / Real.sqrt x) = Real.sqrt x * Real.sqrt y := by calc x * (Real.sqrt y / Real.sqrt x) = (Real.sqrt x)^2 * (Real.sqrt y / Real.sqrt x) := by rw [Real.sq_sqrt hx] _ = Real.sqrt x * Real.sqrt y := by field_simp [hsx.ne'] have hm := mul_le_mul_of_nonneg_left hlog hx rw [hlogid, mul_sub, mul_one, hprod] at hm nlinarith [Real.sq_sqrt hx, Real.sq_sqrt hy]
theorem hellingerSquared_le_relativeEntropy (p q : α → ℝ) (hp : IsProbability p) (hq : IsProbability q) (hs : SupportedBy p q) : hellingerSquared p q ≤ relativeEntropy p q := by have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => sqrt_distance_le_relativeEntropy_term (hp.1 a) (hq.1 a) (hs a)) simpa only [hellingerSquared, relativeEntropy, Finset.sum_add_distrib, Finset.sum_sub_distrib, hp.2, hq.2, sub_add_cancel] using hsum
theorem totalVariation_sq_le_hellingerSquared (p q : α → ℝ) (hp : IsProbability p) (hq : IsProbability q) : totalVariation p q ^ 2 ≤ hellingerSquared p q := by have hfactor : ∀ a, |Real.sqrt (p a) - Real.sqrt (q a)| * (Real.sqrt (p a) + Real.sqrt (q a)) = |p a - q a| := by intro a rw [← abs_of_nonneg (add_nonneg (Real.sqrt_nonneg _) (Real.sqrt_nonneg _)), ← abs_mul] congr 1 nlinarith [Real.sq_sqrt (hp.1 a), Real.sq_sqrt (hq.1 a)] have hcs := Finset.sum_mul_sq_le_sq_mul_sq (Finset.univ : Finset α) (fun a => |Real.sqrt (p a) - Real.sqrt (q a)|) (fun a => Real.sqrt (p a) + Real.sqrt (q a)) simp only [hfactor, sq_abs] at hcs have hpoint : ∀ a, (Real.sqrt (p a) + Real.sqrt (q a)) ^ 2 ≤ 2 * (p a + q a) := by intro a nlinarith [sq_nonneg (Real.sqrt (p a) - Real.sqrt (q a)), Real.sq_sqrt (hp.1 a), Real.sq_sqrt (hq.1 a)] have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => hpoint a) simp only [← Finset.mul_sum, Finset.sum_add_distrib, hp.2, hq.2] at hsum have hnonneg : 0 ≤ ∑ a, (Real.sqrt (p a) - Real.sqrt (q a)) ^ 2 := Finset.sum_nonneg (fun a _ => sq_nonneg _) have hmul := mul_le_mul_of_nonneg_left hsum hnonneg dsimp [totalVariation, hellingerSquared] nlinarith
theorem totalVariation_sq_le_relativeEntropy (p q : α → ℝ) (hp : IsProbability p) (hq : IsProbability q) (hs : SupportedBy p q) : totalVariation p q ^ 2 ≤ relativeEntropy p q := (totalVariation_sq_le_hellingerSquared p q hp hq).trans (hellingerSquared_le_relativeEntropy p q hp hq hs)
theorem posterior_totalVariation_sq_le_log (p w : α → ℝ) (hp : IsProbability p) (hw : ∀ a, 0 ≤ w a) (hw_one : ∀ a, w a ≤ 1) {z : ℝ} (hz : 0 < z) (hmass : ∑ a, p a * w a = z) : totalVariation (posterior p w z) p ^ 2 ≤ Real.log (1 / z) := by exact (totalVariation_sq_le_relativeEntropy _ _ (posterior_isProbability p w hp hw hz hmass) hp (posterior_supportedBy p w z)).trans (posterior_relativeEntropy_le p w hp hw hw_one hz hmass)
open scoped BigOperators
variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq ι]
noncomputable def coordinateMarginal (p : (ι → α) → ℝ) (i : ι) (a : α) : ℝ := by classical exact ∑ x, if x i = a then p x else 0
noncomputable def independentProduct (q : ι → α → ℝ) (x : ι → α) : ℝ := ∏ i, q i (x i)
theorem coordinateMarginal_isProbability (p : (ι → α) → ℝ) (hp : IsProbability p) (i : ι) : IsProbability (coordinateMarginal p i) := by classical constructor · intro a apply Finset.sum_nonneg intro x _ split_ifs · exact hp.1 x · exact le_rfl · simp only [coordinateMarginal] rw [Finset.sum_comm] simpa using hp.2
theorem point_le_coordinateMarginal (p : (ι → α) → ℝ) (hp : IsProbability p) (i : ι) (x : ι → α) : p x ≤ coordinateMarginal p i (x i) := by classical have h := Finset.single_le_sum (f := fun y : ι → α => if y i = x i then p y else 0) (fun y _ => by split_ifs; exact hp.1 y; exact le_rfl) (Finset.mem_univ x) simpa [coordinateMarginal] using h
theorem marginal_expectation (p : (ι → α) → ℝ) (i : ι) (f : α → ℝ) : (∑ x, p x * f (x i)) = ∑ a, coordinateMarginal p i a * f a := by classical simp only [coordinateMarginal, Finset.sum_mul] rw [Finset.sum_comm] apply Finset.sum_congr rfl intro x _ simp [ite_mul]
theorem independentProduct_isProbability (q : ι → α → ℝ) (hq : ∀ i, IsProbability (q i)) : IsProbability (independentProduct q) := by classical constructor · intro x exact Finset.prod_nonneg (fun i _ => (hq i).1 (x i)) · simp only [independentProduct, ← Fintype.prod_sum, (hq _).2, Finset.prod_const_one]
theorem joint_supportedBy_product_coordinateMarginals (p : (ι → α) → ℝ) (hp : IsProbability p) : SupportedBy p (independentProduct (coordinateMarginal p)) := by intro x hx apply Finset.prod_ne_zero_iff.mpr intro i _ exact ne_of_gt ((lt_of_le_of_ne (hp.1 x) (Ne.symm hx)).trans_le (point_le_coordinateMarginal p hp i x))
theorem relativeEntropy_independent_reference (p : (ι → α) → ℝ) (q : ι → α → ℝ) (hp : IsProbability p) (_hq : ∀ i, IsProbability (q i)) (hs : ∀ i, SupportedBy (coordinateMarginal p i) (q i)) : relativeEntropy p (independentProduct q) = relativeEntropy p (independentProduct (coordinateMarginal p)) + ∑ i, relativeEntropy (coordinateMarginal p i) (q i) := by classical have hpoint : ∀ x : ι → α, p x * Real.log (p x / independentProduct q x) = p x * Real.log (p x / independentProduct (coordinateMarginal p) x) + ∑ i, p x * Real.log (coordinateMarginal p i (x i) / q i (x i)) := by intro x by_cases hx : p x = 0 · simp [hx] have hm : ∀ i, coordinateMarginal p i (x i) ≠ 0 := by intro i exact ne_of_gt ((lt_of_le_of_ne (hp.1 x) (Ne.symm hx)).trans_le (point_le_coordinateMarginal p hp i x)) have hqne : ∀ i, q i (x i) ≠ 0 := fun i => hs i (x i) (hm i) have hmp : (∏ i, coordinateMarginal p i (x i)) ≠ 0 := Finset.prod_ne_zero_iff.mpr (fun i _ => hm i) have hqp : (∏ i, q i (x i)) ≠ 0 := Finset.prod_ne_zero_iff.mpr (fun i _ => hqne i) simp only [independentProduct, Real.log_div hx hmp, Real.log_div hx hqp, Real.log_prod (fun i _ => hm i), Real.log_prod (fun i _ => hqne i)] simp_rw [Real.log_div (hm _) (hqne _)] rw [← Finset.mul_sum, Finset.sum_sub_distrib] ring calc relativeEntropy p (independentProduct q) = ∑ x, (p x * Real.log (p x / independentProduct (coordinateMarginal p) x) + ∑ i, p x * Real.log (coordinateMarginal p i (x i) / q i (x i))) := by exact Finset.sum_congr rfl (fun x _ => hpoint x) _ = relativeEntropy p (independentProduct (coordinateMarginal p)) + ∑ i, ∑ x, p x * Real.log (coordinateMarginal p i (x i) / q i (x i)) := by rw [Finset.sum_add_distrib, Finset.sum_comm] rfl _ = relativeEntropy p (independentProduct (coordinateMarginal p)) + ∑ i, relativeEntropy (coordinateMarginal p i) (q i) := by congr 1 apply Finset.sum_congr rfl intro i _ exact marginal_expectation p i (fun a => Real.log (coordinateMarginal p i a / q i a))
theorem coordinate_relativeEntropy_sum_le (p : (ι → α) → ℝ) (q : ι → α → ℝ) (hp : IsProbability p) (hq : ∀ i, IsProbability (q i)) (hs : ∀ i, SupportedBy (coordinateMarginal p i) (q i)) : (∑ i, relativeEntropy (coordinateMarginal p i) (q i)) ≤ relativeEntropy p (independentProduct q) := by rw [relativeEntropy_independent_reference p q hp hq hs] exact le_add_of_nonneg_left (relativeEntropy_nonneg _ _ hp (independentProduct_isProbability _ (coordinateMarginal_isProbability p hp)) (joint_supportedBy_product_coordinateMarginals p hp))
theorem coordinate_totalVariation_sq_sum_le (p : (ι → α) → ℝ) (q : ι → α → ℝ) (hp : IsProbability p) (hq : ∀ i, IsProbability (q i)) (hs : ∀ i, SupportedBy (coordinateMarginal p i) (q i)) : (∑ i, totalVariation (coordinateMarginal p i) (q i) ^ 2) ≤ relativeEntropy p (independentProduct q) := by exact (Finset.sum_le_sum (fun i _ => totalVariation_sq_le_relativeEntropy _ _ (coordinateMarginal_isProbability p hp i) (hq i) (hs i))).trans (coordinate_relativeEntropy_sum_le p q hp hq hs)
theorem posterior_coordinate_supportedBy (q : ι → α → ℝ) (w : (ι → α) → ℝ) (z : ℝ) (i : ι) : SupportedBy (coordinateMarginal (posterior (independentProduct q) w z) i) (q i) := by classical intro a ha hqa apply ha unfold coordinateMarginal apply Finset.sum_eq_zero intro x _ by_cases hxa : x i = a · have hzprod : independentProduct q x = 0 := by exact Finset.prod_eq_zero (Finset.mem_univ i) (by simpa only [hxa] using hqa) simp [hxa, posterior, hzprod] · simp [hxa]
theorem posterior_coordinate_totalVariation_sq_sum_le_log (q : ι → α → ℝ) (hq : ∀ i, IsProbability (q i)) (w : (ι → α) → ℝ) (hw : ∀ x, 0 ≤ w x) (hw_one : ∀ x, w x ≤ 1) {z : ℝ} (hz : 0 < z) (hmass : ∑ x, independentProduct q x * w x = z) : (∑ i, totalVariation (coordinateMarginal (posterior (independentProduct q) w z) i) (q i) ^ 2) ≤ Real.log (1 / z) := by have hp := independentProduct_isProbability q hq exact (coordinate_totalVariation_sq_sum_le _ q (posterior_isProbability _ w hp hw hz hmass) hq (posterior_coordinate_supportedBy q w z)).trans (posterior_relativeEntropy_le _ w hp hw hw_one hz hmass)
theorem posterior_coordinate_totalVariation_sum_le_sqrt (q : ι → α → ℝ) (hq : ∀ i, IsProbability (q i)) (w : (ι → α) → ℝ) (hw : ∀ x, 0 ≤ w x) (hw_one : ∀ x, w x ≤ 1) {z : ℝ} (hz : 0 < z) (hmass : ∑ x, independentProduct q x * w x = z) : (∑ i, totalVariation (coordinateMarginal (posterior (independentProduct q) w z) i) (q i)) ≤ Real.sqrt ((Fintype.card ι : ℝ) * Real.log (1 / z)) := by let d : ι → ℝ := fun i => totalVariation (coordinateMarginal (posterior (independentProduct q) w z) i) (q i) have hsq := posterior_coordinate_totalVariation_sq_sum_le_log q hq w hw hw_one hz hmass have hcs := Finset.sum_mul_sq_le_sq_mul_sq (Finset.univ : Finset ι) d (fun _ => (1 : ℝ)) simp only [mul_one, one_pow, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_one] at hcs have hln : 0 ≤ Real.log (1 / z) := by have hp := independentProduct_isProbability q hq exact (relativeEntropy_nonneg _ _ (posterior_isProbability _ w hp hw hz hmass) hp (posterior_supportedBy _ w z)).trans (posterior_relativeEntropy_le _ w hp hw hw_one hz hmass) have hcard : 0 ≤ (Fintype.card ι : ℝ) := Nat.cast_nonneg _ have hmul := mul_le_mul_of_nonneg_left hsq hcard have hsqrt := Real.sq_sqrt (mul_nonneg hcard hln) have hsqrtpos := Real.sqrt_nonneg ((Fintype.card ι : ℝ) * Real.log (1 / z)) change (∑ i, d i) ≤ _ change (∑ i, d i ^ 2) ≤ _ at hsq change (Fintype.card ι : ℝ) * (∑ i, d i ^ 2) ≤ _ at hmul nlinarith
theorem posterior_coordinate_totalVariation_sq_sum_le_binaryLog (q : ι → α → ℝ) (hq : ∀ i, IsProbability (q i)) (w : (ι → α) → ℝ) (hw : ∀ x, 0 ≤ w x) (hw_one : ∀ x, w x ≤ 1) {z : ℝ} (hz : 0 < z) (hmass : ∑ x, independentProduct q x * w x = z) : (∑ i, totalVariation (coordinateMarginal (posterior (independentProduct q) w z) i) (q i) ^ 2) ≤ Real.log (1 / z) / Real.log 2 := by exact le_binaryLog_of_le_log (Finset.sum_nonneg (fun _ _ => sq_nonneg _)) (posterior_coordinate_totalVariation_sq_sum_le_log q hq w hw hw_one hz hmass)
open scoped BigOperators
variable {α : Type*} [Fintype α]
theorem normalize_isProbability (b : α → ℝ) (hb : ∀ a, 0 ≤ b a) {B : ℝ} (hB : 0 < B) (hmass : ∑ a, b a = B) : IsProbability (fun a => b a / B) := by constructor · intro a exact div_nonneg (hb a) hB.le · simp only [div_eq_mul_inv, ← Finset.sum_mul, hmass, mul_inv_cancel₀ hB.ne']
theorem relativeEntropy_normalize_right (p b : α → ℝ) (hp : IsProbability p) (hs : SupportedBy p b) {B : ℝ} (hB : 0 < B) : relativeEntropy p (fun a => b a / B) = relativeEntropy p b + Real.log B := by have hpoint : ∀ a, p a * Real.log (p a / (b a / B)) = p a * Real.log (p a / b a) + p a * Real.log B := by intro a by_cases hpa : p a = 0 · simp [hpa] have hbne := hs a hpa rw [Real.log_div hpa (div_ne_zero hbne hB.ne'), Real.log_div hbne hB.ne', Real.log_div hpa hbne] ring simp only [relativeEntropy, hpoint, Finset.sum_add_distrib, ← Finset.sum_mul, hp.2, one_mul]
theorem neg_relativeEntropy_le_log_mass (p b : α → ℝ) (hp : IsProbability p) (hb : ∀ a, 0 ≤ b a) (hs : SupportedBy p b) {B : ℝ} (hB : 0 < B) (hmass : ∑ a, b a = B) : -relativeEntropy p b ≤ Real.log B := by have hs' : SupportedBy p (fun a => b a / B) := fun a ha => div_ne_zero (hs a ha) hB.ne' have hnonneg := relativeEntropy_nonneg p (fun a => b a / B) hp (normalize_isProbability b hb hB hmass) hs' rw [relativeEntropy_normalize_right p b hp hs hB] at hnonneg linarith
theorem posterior_weighted_log_inverse_le (p b c : α → ℝ) (hp : IsProbability p) (hb : ∀ a, 0 ≤ b a) {z B : ℝ} (hz : 0 < z) (hB : 0 < B) (hmass : ∑ a, b a = B) (hpost : ∀ a, p a = b a * c a / z) : (∑ a, p a * Real.log (1 / c a)) ≤ Real.log (B / z) := by have hs : SupportedBy p b := by intro a ha hba apply ha rw [hpost, hba, zero_mul, zero_div] have hpoint : ∀ a, p a * Real.log (1 / c a) = p a * Real.log (1 / z) - p a * Real.log (p a / b a) := by intro a by_cases hpa : p a = 0 · simp [hpa] have hbne := hs a hpa have hcne : c a ≠ 0 := by intro hca apply hpa rw [hpost, hca, mul_zero, zero_div] have hratio : p a / b a = c a / z := by rw [hpost] field_simp [hbne, hz.ne'] rw [hratio, Real.log_div hcne hz.ne', Real.log_div one_ne_zero hcne, Real.log_div one_ne_zero hz.ne', Real.log_one] ring have hid : (∑ a, p a * Real.log (1 / c a)) = Real.log (1 / z) - relativeEntropy p b := by simp only [hpoint, Finset.sum_sub_distrib, ← Finset.sum_mul, hp.2, one_mul, relativeEntropy] have hkl := neg_relativeEntropy_le_log_mass p b hp hb hs hB hmass rw [hid, Real.log_div hB.ne' hz.ne', Real.log_div one_ne_zero hz.ne', Real.log_one] linarith
open scoped BigOperators
noncomputable def posteriorOrOriginal {A : Type*} [Fintype A] (p e : A → ℝ) (z : ℝ) : A → ℝ := by classical exact if 0 < z then posterior p e z else p
theorem posteriorOrOriginal_isProbability {A : Type*} [Fintype A] (p e : A → ℝ) (hp : IsProbability p) (he : ∀ a, 0 ≤ e a) {z : ℝ} (hmass : ∑ a, p a * e a = z) : IsProbability (posteriorOrOriginal p e z) := by classical by_cases hz : 0 < z · simpa only [posteriorOrOriginal, ite_eq_left hz] using posterior_isProbability p e hp he hz hmass · simpa only [posteriorOrOriginal, ite_eq_right hz] using hp
theorem mass_mul_posteriorOrOriginal {A : Type*} [Fintype A] (p e : A → ℝ) (hp : IsProbability p) (he : ∀ a, 0 ≤ e a) {c : ℝ} (hmass : ∑ a, p a * e a = c) (x : A) : c * posteriorOrOriginal p e c x = p x * e x := by classical by_cases hc : 0 < c · simp only [posteriorOrOriginal, ite_eq_left hc, posterior] field_simp [hc.ne'] · have hcnonneg : 0 ≤ c := by rw [← hmass] exact Finset.sum_nonneg (fun a _ => mul_nonneg (hp.1 a) (he a)) have hc0 : c = 0 := le_antisymm (le_of_not_gt hc) hcnonneg have hpoint := Finset.single_le_sum (fun a (_ : a ∈ (Finset.univ : Finset A)) => mul_nonneg (hp.1 a) (he a)) (Finset.mem_univ x) rw [hmass, hc0] at hpoint have hzero : p x * e x = 0 := le_antisymm hpoint (mul_nonneg (hp.1 x) (he x)) simp [posteriorOrOriginal, hc0, hzero]
theorem weighted_coordinate_posterior_recombine {I A : Type*} [Fintype I] [Fintype A] [DecidableEq I] [DecidableEq A] (p e : (I → A) → ℝ) (hp : IsProbability p) (he : ∀ x, 0 ≤ e x) {c : ℝ} (hmass : ∑ x, p x * e x = c) (b z : ℝ) (i : I) (a : A) : (b * c / z) * coordinateMarginal (posteriorOrOriginal p e c) i a = (b / z) * ∑ x, if x i = a then p x * e x else 0 := by classical simp only [coordinateMarginal, Finset.mul_sum] apply Finset.sum_congr rfl intro x _ by_cases hxa : x i = a · simp only [ite_eq_left hxa] calc (b * c / z) * posteriorOrOriginal p e c x = (b / z) * (c * posteriorOrOriginal p e c x) := by ring _ = (b / z) * (p x * e x) := by rw [mass_mul_posteriorOrOriginal p e hp he hmass x] · simp [hxa]
variable {J I A : Type*}variable [Fintype J] [Fintype I] [Fintype A] [DecidableEq I]
theorem side_information_bound (w b c : J → ℝ) (q : J → I → A → ℝ) (e : J → (I → A) → ℝ) (hw : IsProbability w) (hb : ∀ j, 0 ≤ b j) (hq : ∀ j i, IsProbability (q j i)) (he : ∀ j x, 0 ≤ e j x) (he_one : ∀ j x, e j x ≤ 1) (hmass : ∀ j, ∑ x, independentProduct (q j) x * e j x = c j) {z B : ℝ} (hz : 0 < z) (hB : 0 < B) (hbase : ∑ j, b j = B) (hweight : ∀ j, w j = b j * c j / z) : (∑ i, totalVariation (fun ja : J × A => w ja.1 * coordinateMarginal (posteriorOrOriginal (independentProduct (q ja.1)) (e ja.1) (c ja.1)) i ja.2) (fun ja : J × A => w ja.1 * q ja.1 i ja.2)) ≤ Real.sqrt ((Fintype.card I : ℝ) * Real.log (B / z)) := by classical let d : J → I → ℝ := fun j i => totalVariation (coordinateMarginal (posteriorOrOriginal (independentProduct (q j)) (e j) (c j)) i) (q j i) have hbudget : ∀ j, w j * (∑ i, d j i ^ 2) ≤ w j * Real.log (1 / c j) := by intro j by_cases hwzero : w j = 0 · simp [hwzero] have hcne : c j ≠ 0 := by intro hczero apply hwzero rw [hweight j, hczero, mul_zero, zero_div] have hcnonneg : 0 ≤ c j := by rw [← hmass j] exact Finset.sum_nonneg (fun x _ => mul_nonneg ((independentProduct_isProbability (q j) (hq j)).1 x) (he j x)) have hcpos : 0 < c j := lt_of_le_of_ne hcnonneg (Ne.symm hcne) have hlocal := posterior_coordinate_totalVariation_sq_sum_le_log (q j) (hq j) (e j) (he j) (he_one j) hcpos (hmass j) have hweighted := mul_le_mul_of_nonneg_left hlocal (hw.1 j) simpa only [d, posteriorOrOriginal, ite_eq_left hcpos] using hweighted have hcs := weighted_coordinate_sum_sq_le w d (fun j => Real.log (1 / c j)) hw hbudget have hlog := posterior_weighted_log_inverse_le w b c hw hb hz hB hbase hweight have hsq : (∑ i, ∑ j, w j * d j i)^2 ≤ (Fintype.card I : ℝ) * Real.log (B / z) := hcs.trans (mul_le_mul_of_nonneg_left hlog (Nat.cast_nonneg _)) have htv : ∀ i, totalVariation (fun ja : J × A => w ja.1 * coordinateMarginal (posteriorOrOriginal (independentProduct (q ja.1)) (e ja.1) (c ja.1)) i ja.2) (fun ja : J × A => w ja.1 * q ja.1 i ja.2) = ∑ j, w j * d j i := by intro i exact totalVariation_joint_common_weights w (fun j => coordinateMarginal (posteriorOrOriginal (independentProduct (q j)) (e j) (c j)) i) (fun j => q j i) hw.1 simp_rw [htv] have hradicand : 0 ≤ (Fintype.card I : ℝ) * Real.log (B / z) := (sq_nonneg _).trans hsq have hsqrt := Real.sq_sqrt hradicand have hsqrt_nonneg := Real.sqrt_nonneg ((Fintype.card I : ℝ) * Real.log (B / z)) nlinarith
variable {T V : Type*} [Fintype T] [Fintype V] [Nonempty V]
theorem finite_side_information_bound (pT : T → ℝ) (q : T → I → A → ℝ) (e : T × V → (I → A) → ℝ) (c w : T × V → ℝ) (hpT : IsProbability pT) (hq : ∀ t i, IsProbability (q t i)) (he : ∀ tv x, 0 ≤ e tv x) (he_sum : ∀ t x, (∑ v, e (t, v) x) ≤ 1) (hc : ∀ tv, ∑ x, independentProduct (q tv.1) x * e tv x = c tv) {z : ℝ} (hz : 0 < z) (hZ : ∑ tv, pT tv.1 * c tv = z) (hweight : ∀ tv, w tv = pT tv.1 * c tv / z) : (∑ i, totalVariation (fun tva : (T × V) × A => w tva.1 * coordinateMarginal (posteriorOrOriginal (independentProduct (q tva.1.1)) (e tva.1) (c tva.1)) i tva.2) (fun tva : (T × V) × A => w tva.1 * q tva.1.1 i tva.2)) ≤ Real.sqrt ((Fintype.card I : ℝ) * (Real.log (Fintype.card V : ℝ) + Real.log (1 / z))) := by classical have hcnonneg : ∀ tv, 0 ≤ c tv := by intro tv rw [← hc tv] exact Finset.sum_nonneg (fun x _ => mul_nonneg ((independentProduct_isProbability (q tv.1) (hq tv.1)).1 x) (he tv x)) have hw : IsProbability w := by constructor · intro tv rw [hweight tv] exact div_nonneg (mul_nonneg (hpT.1 tv.1) (hcnonneg tv)) hz.le · simp_rw [hweight, div_eq_mul_inv] rw [← Finset.sum_mul, hZ, mul_inv_cancel₀ hz.ne'] have he_one : ∀ tv x, e tv x ≤ 1 := by intro tv x have hsingle : e tv x ≤ ∑ v, e (tv.1, v) x := Finset.single_le_sum (fun v _ => he (tv.1, v) x) (Finset.mem_univ tv.2) exact hsingle.trans (he_sum tv.1 x) have hB : 0 < (Fintype.card V : ℝ) := Nat.cast_pos.mpr Fintype.card_pos have hbase : (∑ tv : T × V, pT tv.1) = (Fintype.card V : ℝ) := by simp only [Fintype.sum_prod_type, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, ← Finset.mul_sum, hpT.2, mul_one] have h := side_information_bound w (fun tv : T × V => pT tv.1) c (fun tv => q tv.1) e hw (fun tv => hpT.1 tv.1) (fun tv => hq tv.1) he he_one hc hz hB hbase hweight have hlog : Real.log ((Fintype.card V : ℝ) / z) = Real.log (Fintype.card V : ℝ) + Real.log (1 / z) := by rw [Real.log_div hB.ne' hz.ne', Real.log_div one_ne_zero hz.ne', Real.log_one] ring simpa only [hlog] using h
end MinUncutGames.Foundations.Information
end OAI12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import Mathlibimport OAI.Computability.MinUncut.Machines.PoweringMachineRotor
namespace OAI
sectionnamespace MinUncutGames.Foundations.Complexity.PoweringGlobalEnumeration
open PoweringMachineLoop PoweringMachineInitialize
def headerTapeEquiv : HeaderTape ≃ Fin 4 where toFun | .source => 0 | .counter => 1 | .vertices => 2 | .darts => 3 invFun i := if i = 0 then .source else if i = 1 then .counter else if i = 2 then .vertices else .darts left_inv tape := by cases tape <;> rfl right_inv i := by fin_cases i <;> rfl
def unitTapeEquiv : Unit ≃ Fin 1 where toFun _ := 0 invFun _ := () left_inv u := by cases u; rfl right_inv i := (Fin.eq_zero i).symm
def sharedTapeEquiv (max : Nat) : PoweringMachineTapes.Tape max ≃ Fin (11 + max) := finSumFinEquiv
def extraTapeEquiv (max : Nat) : ExtraTape max ≃ Fin (11 + max + 1) := (Equiv.sumCongr (sharedTapeEquiv max) unitTapeEquiv).trans finSumFinEquiv
def globalTapeEquiv (max : Nat) : GlobalTape max ≃ Fin (4 + (11 + max + 1)) := (Equiv.sumCongr headerTapeEquiv (extraTapeEquiv max)).trans finSumFinEquiv
def enumeration (max : Nat) : Fin (4 + (11 + max + 1)) ≃ GlobalTape max := (globalTapeEquiv max).symm
@[simp] theorem globalTapeEquiv_enumeration (max : Nat) (i : Fin (4 + (11 + max + 1))) : globalTapeEquiv max (enumeration max i) = i := (globalTapeEquiv max).apply_symm_apply i
@[simp] theorem enumeration_globalTapeEquiv (max : Nat) (tape : GlobalTape max) : enumeration max (globalTapeEquiv max tape) = tape := (globalTapeEquiv max).symm_apply_apply tape
@[simp] theorem source_index (max : Nat) : (globalTapeEquiv max (.inl .source)).val = 0 := rfl
@[simp] theorem counter_index (max : Nat) : (globalTapeEquiv max (.inl .counter)).val = 1 := rfl
@[simp] theorem vertices_index (max : Nat) : (globalTapeEquiv max (.inl .vertices)).val = 2 := rfl
@[simp] theorem darts_index (max : Nat) : (globalTapeEquiv max (.inl .darts)).val = 3 := rfl
theorem sharedRole_index (max : Nat) (i : Fin 11) : (globalTapeEquiv max (.inr (.inl (.inl i)))).val = 4 + i.val := rfl
theorem trajectory_index (max : Nat) (i : Fin max) : (globalTapeEquiv max (.inr (.inl (.inr i)))).val = 4 + (11 + i.val) := rfl
@[simp] theorem finalOutput_index (max : Nat) : (globalTapeEquiv max (finalOutput max)).val = 4 + (11 + max) := rfl
theorem card_globalTape (max : Nat) : Fintype.card (GlobalTape max) = 4 + (11 + max + 1) := by simpa only [Fintype.card_fin] using Fintype.card_congr (globalTapeEquiv max)
theorem natCard_globalTape (max : Nat) : Nat.card (GlobalTape max) = 4 + (11 + max + 1) := by simpa only [Nat.card_fin] using Nat.card_congr (globalTapeEquiv max)
def allTapes (max : Nat) : List (GlobalTape max) := List.ofFn (enumeration max)
theorem allTapes_length (max : Nat) : (allTapes max).length = 4 + (11 + max + 1) := by simpa only [allTapes] using (List.length_ofFn (f := enumeration max))
theorem mem_allTapes (max : Nat) (tape : GlobalTape max) : tape ∈ allTapes max := by change tape ∈ List.ofFn (enumeration max) apply List.mem_ofFn.mpr exact ⟨globalTapeEquiv max tape, enumeration_globalTapeEquiv max tape⟩
end MinUncutGames.Foundations.Complexity.PoweringGlobalEnumeration
end
end OAIlean/OAI/Computability/MinUncut/Estimates/RowListBridge.leanAdded+63
lean/OAI/Computability/MinUncut/Estimates/SamplerAssembly.leanAdded+93
lean/OAI/Computability/MinUncut/Estimates/SamplerCost.leanAdded+106
lean/OAI/Computability/MinUncut/Estimates/SecondFailureIndicator.leanAdded+259
lean/OAI/Computability/MinUncut/Estimates/SelectedProject.leanAdded+59
lean/OAI/Computability/MinUncut/Estimates/SelectedProjectSliceContinuous.leanAdded+53
lean/OAI/Computability/MinUncut/Estimates/SelectedSyntax.leanAdded+57
lean/OAI/Computability/MinUncut/Estimates/SingleRow.leanAdded+125
lean/OAI/Computability/MinUncut/Estimates/TM2Costed.leanAdded+724
lean/OAI/Computability/MinUncut/Estimates/TableLawPacking.leanAdded+92
lean/OAI/Computability/MinUncut/Estimates/TableTestFunctions.leanAdded+101
lean/OAI/Computability/MinUncut/Estimates/TemplateExpressions.leanAdded+376
lean/OAI/Computability/MinUncut/Estimates/UniformAlgebra.leanAdded+90
lean/OAI/Computability/MinUncut/Estimates/UniformBoolean.leanAdded+97
lean/OAI/Computability/MinUncut/Estimates/UniformEquation.leanAdded+288
lean/OAI/Computability/MinUncut/Estimates/UniformEquationOutput.leanAdded+298
lean/OAI/Computability/MinUncut/Estimates/UniformFaceArray.leanAdded+36
lean/OAI/Computability/MinUncut/Estimates/UniformGrid.leanAdded+483
lean/OAI/Computability/MinUncut/Estimates/UniformOutput.leanAdded+27
lean/OAI/Computability/MinUncut/Estimates/UniformProduct.leanAdded+65
lean/OAI/Computability/MinUncut/Estimates/UniformRestrict.leanAdded+195
lean/OAI/Computability/MinUncut/Estimates/UniformSets.leanAdded+59
lean/OAI/Computability/MinUncut/Estimates/UniformTransport.leanAdded+119
lean/OAI/Computability/MinUncut/Estimates/WeightedTestLaw.leanAdded+187
lean/OAI/Computability/MinUncut/Games/Actual.leanAdded+688
lean/OAI/Computability/MinUncut/Games/AdaptiveKernel.leanAdded+83
lean/OAI/Computability/MinUncut/Games/AffineLabels.leanAdded+91
lean/OAI/Computability/MinUncut/Games/Basic.leanAdded+684
lean/OAI/Computability/MinUncut/Games/FinalCNFHeader.leanAdded+733
lean/OAI/Computability/MinUncut/Games/FinalCNFOutput.leanAdded+406
lean/OAI/Computability/MinUncut/Games/FinalCNFPattern.leanAdded+103
lean/OAI/Computability/MinUncut/Games/FinalCNFStream.leanAdded+688
lean/OAI/Computability/MinUncut/Games/FiniteNoise.leanAdded+94
lean/OAI/Computability/MinUncut/Games/GraphCounterModel.leanAdded+563
lean/OAI/Computability/MinUncut/Games/GraphIterationBounds.leanAdded+77
lean/OAI/Computability/MinUncut/Games/HintSections.leanAdded+83
lean/OAI/Computability/MinUncut/Games/HintSimulation.leanAdded+154
lean/OAI/Computability/MinUncut/Games/HintSoundness.leanAdded+74
lean/OAI/Computability/MinUncut/Games/IncidenceProbability.leanAdded+527
lean/OAI/Computability/MinUncut/Games/JointCoefficient.leanAdded+86
lean/OAI/Computability/MinUncut/Games/JointHintBound.leanAdded+141
lean/OAI/Computability/MinUncut/Games/JointHintSampling.leanAdded+74
lean/OAI/Computability/MinUncut/Games/JointInner.leanAdded+208
lean/OAI/Computability/MinUncut/Games/KernelSampling.leanAdded+208
lean/OAI/Computability/MinUncut/Games/LabelBound.leanAdded+267
lean/OAI/Computability/MinUncut/Games/MaskRowKernel.leanAdded+143
lean/OAI/Computability/MinUncut/Games/OuterQuestions.leanAdded+757
lean/OAI/Computability/MinUncut/Games/Parameters.leanAdded+110
lean/OAI/Computability/MinUncut/Games/Pinsker.leanAdded+517
lean/OAI/Computability/MinUncut/Games/PoweringGlobalEnumeration.leanAdded+91